Adding to a stream file

I have a problem adding text to a file. I open ofstreamin add mode, but 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 is the right constructor ofstreamto add to a file?

+8
source share
2 answers

I use a very convenient 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 add something simple:

filePutContents("./yourfile.txt","content",true);

Using this function, you do not need to worry about opening / closing. Altho should not be used in large cycles.

+11
source

Use ios_base::appinstead ios_base::ateas ios_base::openmodefor the constructor ofstream.

+7
source

All Articles