Adequetely safe method of overwriting a save file?
c++, file, save
Solution
As others have said, keep the existing file around, and write to a fresh file. If it's very important (that is, the user can't possibly recover the information), make sure that there is a "backup" file around as well (e.g. if your program saves `abc.config`, leave an `abc.old.config` or `abc.backup` [if you want guarantees that the name works everywhere, `.cfg` and `.bak` may be better choices]).
When you write the file, put some sort of endmarker in the file, so that you can be sure that the file is complete. If you want to avoid "user editing" of the file, you may also want to have a checksum of the content (sha1, md5 or similar). If the endmarker isn't there, or the checksum is wrong, then you know that the file is "bad", so don't use it and go for the backup.
- Write the new content to a temporary file (e.g. `fstream fout("abc.tmp");`)
- Delete the backup file (if it exists) (e.g. `remove("abc.bak");`)
- Rename the now old file to the backup name (e.g. `rename("abc.cfg", "abc.bak");`)
- Rename the new file to the old one (e.g. `rename("abc.tmp", "abc.cfg"`);
For ALL steps (in particular writing the actual data), check for errors. You need to decide where it is OK to get errors and where it is not (`remove` of a file that doesn't exist is OK, for example, but if `rename` doesn't work you probably should stop, or you may end up with something bad).
When loading the file, check all steps, if it goes wrong, go back to the backup file.
Problem
Using `cstdio`, what is the safest way of overwriting a file? 'safe' in this case meaning that there's no chance the file will become incomplete or corrupted; the file will either be the completely overwritten, or it will be the old file should something have gone awry. I imagine the best way to do this, would be to create a temporary intermediate file, then overwrite the old file once that intermediate is complete. If that actually is the best way though, there's a few other problems that'd seem possible, if albeit rare. - How would I know to use this other file should the program quit while overwriting? - How would I know to NOT use the other file should the program quit during it's creation? - How would I know the original file or the intermediate is in an undefined state (since it may fail in a way that remains readable but the data it contains is subtly wrong)? I imagine there's a single good practice for this, but I haven't been able to find it. This is for saved game data; there's only one file, and the entire file is overwritten every time as well, there are no partial overwrites or appending to worry about.