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
  • 18,940
  • 49
  • 129
  • 194

4 Answers4

10
logging.open(FILENAME, std::ios_base::app); 
Alexey Malistov
  • 25,701
  • 13
  • 63
  • 85
3

You have to open the file in append mode:

logging.open(FILENAME, std::ios::app);
Drew Frezell
  • 2,466
  • 20
  • 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
  • 34,649
  • 7
  • 57
  • 81
0

do you try ? something like that

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