6

In C++, I need to write to an existing file and keep the previous content there.

This is what I have done:

std::ofstream logging;

logging.open(FILENAME);

logging << "HELLO\n";

logging.close();

but then my previous text is overwritten (gone). What did I do wrong?

Thanks in advance.

olidev
  • 20,058
  • 51
  • 133
  • 197

4 Answers4

10
logging.open(FILENAME, std::ios_base::app); 
Alexey Malistov
  • 26,407
  • 13
  • 68
  • 88
3

You have to open the file in append mode:

logging.open(FILENAME, std::ios::app);
Drew Frezell
  • 2,628
  • 21
  • 13
1

By default the "opening mode" for a file is overwrite. Try opening the file in append mode

The second parameter of open is an enum bitflag. The two options you should check out are:

  • app - seek to the file end before each write
  • ate - seek to the file end after open

    logging.open(FILENAME, std::ios::app|std::ate);

luke
  • 36,103
  • 8
  • 58
  • 81
0

do you try ? something like that

myFile.open( "file.txt", ios::out | ios::app );
Sanja Melnichuk
  • 3,465
  • 3
  • 25
  • 46