简体   繁体   中英

How to append to a file in C++?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM