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?
2 Answers
I use a very handy function (similar to PHP file_put_contents)
// Usage example: filePutContents("./yourfile.txt", "content", true); void filePutContents(const std::string& name, const std::string& content, bool append = false) { std::ofstream outfile; if (append) outfile.open(name, std::ios_base::app); else outfile.open(name); outfile << content; } When you need to append something just do:
filePutContents("./yourfile.txt","content",true); Using this function you don't need to take care of opening/closing. Altho it should not be used in big loops
3Use ios_base::app instead of ios_base::ate as ios_base::openmode for ofstream's constructor.