下面是一个例子来说明这个问题:
// Create/truncate file and save '1'
const string NAME = "example.txt";
fstream file(NAME.c_str(), ios::out | ios::trunc);
file << '1';
file.close();
// Re-open file and output its only line
file.open(NAME.c_str(), ios::in | ios::out | ios::app);
string text;
getline(file, text);
cout << "Read \"" << text << "\"" << endl;
// OUTPUTS: Read "1"
// (Try to) Append '2'
file << '2';
file.seekg(0);
getline(file, text);
cout << "Read \"" << text << "\"" << endl;
// OUTPUTS: Read "1"
// (Try to) Append '3'
file.clear(ios::goodbit); /*** SHOULD IT BE NECESSARY TO CLEAR THIS FLAG? ***/
file << '3';
file.seekg(0);
getline(file, text);
cout << "Read \"" << text << "\"" << endl;
// OUTPUTS: Read "13"
我对包含一行我不太了解的代码感到有些不安!
提前致谢。