How to append to a file in C++?

Viewed 4378

I want to print some data to a file with a few separate calls. I noticed that the default behaviour for a write overwrites the previously written data.

#include <iostream>
#include <fstream>
using namespace std;

void hehehaha (){
     ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();

}
int main () {
    for(int i=0; i <3 ; i++){
        hehehaha();}

  return 0;
}

this code writes only one line Writing this to a file. but what I want is the following:

Writing this to a file.
Writing this to a file.
Writing this to a file.
2 Answers

Open the file in app mode instead myfile.open("example.txt", std::ios_base::app);

The default open mode for ofstream is plain out, which recreates the file from scratch (if the file exists, its contents is truncated).

To append to a file you need to use the app mode, or add the flag ate.

The table in this open reference is quite helpful to understand the open-modes and what they do.

Related