Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

appending to a file with ofstream [duplicate]

Tags:

c++

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?

like image 869
Wojtek Avatar asked Sep 28 '14 12:09

Wojtek


People also ask

How do I append a file with ofstream?

In order for us to append to a file, we must put the ofstream() function in append mode, which we explain in the next paragraph. With the full line, ofstream writer("file1. txt", ios::app);, we now create a connection to open up the file1. txt file in order to append contents to the file.

How do you append to a file in C++?

Begin Open that file a1. txt as output file stream class object to perform output operation in append mode using fout file reference. If the file exists then Appending text to that file. Close fout.

Does ofstream truncate?

It truncates by default.

What is Rdbuf C++?

basic_ios::rdbufManages the associated stream buffer. 1) Returns the associated stream buffer. If there is no associated stream buffer, returns a null pointer.


1 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

like image 91
dynamic Avatar answered Sep 20 '22 05:09

dynamic