Safe Save for file data

jwatte's picture

Sometimes, you may find that you're trying to re-write an existing file, but if you write less data than was in the file originally, there will be old data left over at the end of the file. However, this shows a bigger problem with your file handling.

You should generally not re-write the same file in place. Instead, use a "safe save," where you do the following:

To save:

1) Open with CreateAlways (so it's truncated) a file named "MyFile.tmp"
2) Write data to MyFile.tmp, and close/flush
3) Remove the original "MyFile.dat" file
4) Rename "MyFile.tmp" to "MyFile.dat"

To load:

1) Open with OpenRead a file named "MyFile.dat"
2) If that fails, open with OpenRead a file named "MyFile.tmp"
3) If that fails, then this is the first time you were run; return default data
4) Read data from the opened file, close, and return

This means that, if you crash before the "MyFile.dat" file is removed when writing, the old data will be intact. If you crash after the "MyFile.dat" is removed, you will get the new data, because removing MyFile.dat happens after the new ".tmp" file is properly flushed to disk. Renaming is an atomic operation in the file system, so there's no chance of losing the file during rename.