阅读文本文件 - fopen与ifstream

时间:2011-06-19 00:38:41

标签: c++ file fopen ifstream

谷歌搜索文件输入我发现了两种从文件输入文本的方法--fopen和ifstream。以下是两个片段。我有一个文本文件,由一行和一个我需要读入的整数组成。我应该使用fopen还是ifstream?

SNIPPET 1 - FOPEN

FILE * pFile = fopen ("myfile.txt" , "r");
char mystring [100];
if (pFile == NULL) 
{
    perror ("Error opening file");
}
else 
{
    fgets (mystring , 100 , pFile);
    puts (mystring);
    fclose (pFile);
}

SNIPPET 2 - IFSTREAM

string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
    while ( myfile.good() )
    {
        getline (myfile,line);
        cout << line << endl;
    }
    myfile.close();
}
else 
{  
    cout << "Unable to open file"; 
}

2 个答案:

答案 0 :(得分:28)

由于这被标记为C ++,我会说ifstream。如果它被标记为C,我会选择fopen:P

答案 1 :(得分:16)

我更喜欢ifstream,因为它比fopen更加模块化。假设您希望从流中读取的代码也从字符串流或任何其他istream中读取。你可以这样写:

void file_reader()
{ 
    string line;
    ifstream myfile ("example.txt");
    if (myfile.is_open())
    {
        while (myfile.good())
        {
          stream_reader(myfile);
        }
        myfile.close();
    }
    else 
    {  
        cout << "Unable to open file"; 
    }
}

void stream_reader(istream& stream)
{
    getline (stream,line);
    cout << line << endl;
}

现在,您可以在不使用真实文件的情况下测试stream_reader,或者使用它来读取其他输入类型。这对fopen来说要困难得多。