我在将文本追加到文件时遇到了问题。我以追加模式打开了ofstream
,但它只包含最后一行,而不是三行:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream file("sample.txt");
file << "Hello, world!" << endl;
file.close();
file.open("sample.txt", ios_base::ate);
file << "Again hello, world!" << endl;
file.close();
file.open("sample.txt", ios_base::ate);
file << "And once again - hello, world!" << endl;
file.close();
string str;
ifstream ifile("sample.txt");
while (getline(ifile, str))
cout << str;
}
// output: And once again - hello, world!
那么对于向文件进行追加操作,正确的ofstream
构造函数是什么?