appending to a file with ofstream

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


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

Tags:

C++