I have a problem with appending a text to a file. I open an ofstream
in append mode, still instead of three lines it contains only the last:
#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!
So what's the correct ofstream
constructor for appending to a file?