Search code examples
c++fstream

proper use of stream in a computationally intensive program


I have a program that may take up to 3-4 hours to finish. Underway I need to output various information into a general file "info.txt". Here is how I do it currently

char dateStr [9];
char timeStr [9];
_strdate(dateStr);
_strtime(timeStr);

ofstream infoFile("info.txt", ios::out);
infoFile << "foo @ " << timeStr << " , " << dateStr << endl;
infoFile.close();

This I do five times during a single run. My question is the following: Is it most proper (efficiency-wise and standard-wise) to

  1. close infoFile after each output (and, consequently, use five ofstreams infoFile1, infoFile2, ..., infoFile5, one for each time I output)
  2. or only to use "infoFile" and, consequently, have it open during the entire run?

EDIT: By "a single run" I mean a single run of the program. So by "five times during a single run" I mean that I output something to info.txt when running the program once (which takes 3-4 hours).


Solution

  • It's not really clear what you're trying to do. If the code you post does what you want, it's certainly the best solution. If you want the values appended, then you might want to keep the file open.

    Some other considerations:

    • unless you close the file or flush the data, external programs may not see the data immediately.

    • When you open the file, any existing file with that name will be truncated: an external program which tries to read the file at precisely this moment won't see anything.

    • Flushing after each output (automatic if you use std::endl), and seeking to the start before each output, will solve the previous problem (and if the data is as small as it seems, the write will be atomic), but could result in misleading data if the values written have different lengths---the file length will not be shortened. (Probably not the case here, but something to be considered.)

    With regards to performance: you're talking about an operation which lasts at most a couple of milliseconds, and takes place once or twice an hour. Whether it takes one millisecond, or ten, is totally irrelevant.