为什么我不能在Mac OS X上阅读和追加std :: fstream?

And*_*ack 2 c++ fstream stl cross-platform

考虑以下C++程序,它接受一个文件并打印每一行.它是一个更大程序的片段,我后来根据我看到的内容附加到该文件.

#include <fstream>
using std::fstream;
#include <iostream>
#include <string>
using std::string;

int main()
{
 fstream file("file.txt", fstream::in | fstream::out | fstream::app);

 string line;
 while (std::getline(file, line))
  std::cerr << line << std::endl;

 return 0;
}
Run Code Online (Sandbox Code Playgroud)

现在应用此版本file.txt(第一行有一个单词,后跟换行符):

Rain
Run Code Online (Sandbox Code Playgroud)

在我的机器(Snow Leopard)上,它什么都没打印出来.仔细观察,第一次调用getline失败了.奇怪的是,如果我添加第二行也会失败:仍然没有打印出来!

谁能解开这个谜团?

小智 9

当你说:

fstream file("file.txt", fstream::in | fstream::out | fstream::app);
Run Code Online (Sandbox Code Playgroud)

你以附加模式打开文件 - 即最后.只需在读取模式下打开它:

fstream file("file.txt", fstream::in );
Run Code Online (Sandbox Code Playgroud)

或使用ifstream:

ifstream file("file.txt" );
Run Code Online (Sandbox Code Playgroud)

当然,正如Earwicker所说,你应该总是测试开放是否成功.

如果您决定以追加模式打开,则可以显式移动读取指针:

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main() {
    fstream file( "afile.txt", ios::in | ios::out | ios::app );
    if ( ! file.is_open()  ) {
        cerr << "open failed" << endl;
        return 1;
    }
    else {
        file.seekg( 0, ios::beg );   // move read pointer
        string line;
        while( getline( file, line ) ) {
            cout << line << endl;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:似乎在文件打开时使用的标志组合导致实现特定的行为.上面的代码适用于Windows上的g ++,但不适用于Linux上的g ++.