【问题标题】:Reading a text file - fopen vs. ifstream读取文本文件 - fopen 与 ifstream
【发布时间】:2011-09-17 23:51:40
【问题描述】:

谷歌搜索文件输入我发现了两种从文件输入文本的方法 - fopen 和 ifstream。下面是两个sn-ps。我有一个文本文件,其中包含需要读取的整数的一行。我应该使用 fopen 还是 ifstream?

片段 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);
}

片段 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"; 
}

【问题讨论】:

    标签: c++ file fopen ifstream


    【解决方案1】:

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

    【讨论】:

    • 我认为 C 接口对于读取文件来说更干净,但无论如何 +1。
    【解决方案2】:

    我更喜欢 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 来说要困难得多。

    【讨论】:

    • 为什么void stream_reader(FILE *stream) { fgets(line, len, stream); puts(line); } 本质上不一样?
    • 是否可以在不调用 fopen 或 tmpfile 的情况下创建 FILE*?我不相信,但我可能错了。由于stream_reader 的操作只需要一个流,而不是一个文件,我宁愿不要通过让它需要FILE* 来过度约束它。例如,在单元测试中,将字符串流而不是FILE* 传递给它可能更容易。
    • 是的,从这个角度来看,C 版本受到更严格的限制——至少在标准中没有规定 FILE * 指的是字符串而不是文件(尽管有些库有至少在内部提供/使用了相当长的一段时间)。如果你真的需要避免这种情况,你可以传入一个指向函数的指针来进行写入,但这肯定更笨拙。
    • 这个响应肯定是 +1 - 我在代码中使用 ostream 来实现相同的模块化 - 能够决定是否要将数据输出到文件、终端等。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多