5

I'm doing a numerical simulation of gravity in C++ and I want to back up my results every time a single step is counted.

However, the way I do it now, the programm always overwrites the file. I guess I would be able to solve in by always saving the text in a different file or variable, but I wonder if there's an easier way to open a text file so that I wouldn't overwrite it.

My current "back-up code" looks like this:

fstream log;
log.open ("log.txt");
if (log.is_open())
{...
  ...
  log.close();
}
roalz
  • 2,699
  • 3
  • 25
  • 42
Tom83B
  • 2,059
  • 4
  • 18
  • 28

4 Answers4

12

Open the stream in append-mode:

log.open("log.txt", fstream::app);

This will simply append the new output with the existing, giving you one big log file that grows over time.

One suggestion (if you're not doing it already) is to include some kind of timestamp in the logging data, so that when you're reading the file, you can correlate the logged data to a run of the program.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • Thanks for the suggestion. I do plan on doing this in my programm. However, the code you sent doesn't work simply because the file doesn't open. I've set a condition - if the file isn't open, cout<<0. Wrote 1 before, now my command line is full of zeros... :( – Tom83B Nov 11 '10 at 14:53
3

Use log.open("log.txt", fstream::app) for appending to file.

Read this reference for further info.

If you need a sophisticated mechanism for logging and timestamping, there's a useful SO post about logging frameworks for C++. Pantheios got the accepted answer.

Community
  • 1
  • 1
darioo
  • 46,442
  • 10
  • 75
  • 103
  • I'd prefer if I managed to do the logging mechanism myself - even if a little (/ a lot) worse. By the way I checked the link and the source code doesn't work... I compiled it and it didn't work. When I checked it with the is_open() function, it returned 0 – Tom83B Nov 11 '10 at 15:43
1

Since the autor seemed to have problems with the suggested answers I'll add another one.

ofstream log;
log.open("log.txt", ofstream::app);

I guess working with the explicit stream

ifstream

and

ofstream

sometimes works better. Although I don't know the reason.

PascExchange
  • 113
  • 6
0

Set the mode to append. See this: http://www.cplusplus.com/reference/iostream/fstream/open/

caveman
  • 1,755
  • 1
  • 14
  • 19