In the program, I download data from the Internet, and this data needs to be saved to disk. I want to know: if writing data to files using std::ofstream is transactional on Windows OS or is it possible that in case of system failure only part of the data will be written to the disk at the time of writing the data?
I tried to google for the answer but didn't find anything.
No, writing to a file, in general, is not atomic, especially when using high level objects like std::ofstream
, which does its internal buffering and calls upon the underlying operating system to write out the contents of the file in discrete, separate chunks.
The classical approach to implementing reliable atomicity, in this situation, is to write out the new file under a temporary name. When the entire contents are written the file gets closed, then renamed to its permanent name. In this manner the designated file's contents are always read as complete. Either the complete file gets renamed, or not, there is no middle state. If the state is interrupted, the partially-complete file is ignored, and simply gets overwritten on Take 2.
At least, of course, barring the involvement of pesky cosmic rays, and little gnomes, that mess up the rename operation just at the right time, to crash the entire system and leaving its storage in a state of strewn garbage, all over the place. All bets are off in that case, it goes without saying.