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();
}
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With