Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append to a file in C++?

Tags:

c++

c++11

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.
like image 381
ahmad sedigh Avatar asked Oct 26 '25 08:10

ahmad sedigh


1 Answers

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

like image 68
Pani Avatar answered Oct 29 '25 00:10

Pani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!