27

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?

Wojtek
  • 801
  • 1
  • 9
  • 13

2 Answers2

46

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

dynamic
  • 46,985
  • 55
  • 154
  • 231
  • 1
    What's the difference between `std::ios_base::app` and `std::io::app`? – Alexander Jun 05 '18 at 12:00
  • 1
    `app` seeks to end before each write, whereas `ate` opens and seeks to end immediately after opening. – Hope Oct 10 '18 at 13:42
  • +1 for php reference. PHP may be hated in some places but it has many many useful little functions like this that make the life of a dev easier :) – AntonioCS Jan 03 '22 at 09:14
18

Use ios_base::app instead of ios_base::ate as ios_base::openmode for ofstream's constructor.

Dev Null
  • 4,731
  • 1
  • 30
  • 46
macfij
  • 3,093
  • 1
  • 19
  • 24