Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing into a text file without overwriting it

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();
}
like image 927
Tom83B Avatar asked Nov 11 '10 14:11

Tom83B


3 Answers

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.

like image 195
unwind Avatar answered Nov 06 '22 17:11

unwind


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.

like image 40
darioo Avatar answered Nov 06 '22 17:11

darioo


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.

like image 26
PascExchange Avatar answered Nov 06 '22 15:11

PascExchange