How to append text to a text file in C++?

Ahmad Farid picture Ahmad Farid · Mar 6, 2010 · Viewed 294.2k times · Source

How to append text to a text file in C++? And create a new text file if it does not already exist and append text to it if it does exist.

Answer

Bertrand Marron picture Bertrand Marron · Mar 6, 2010

You need to specify the append open mode like

#include <fstream>

int main() {  
  std::ofstream outfile;

  outfile.open("test.txt", std::ios_base::app); // append instead of overwrite
  outfile << "Data"; 
  return 0;
}