I've written code that saves progress in my game, but one of my biggest fears is the brief window of time during saving when that data might become corrupted should the computer crash or lose power.
Is there standard methodology using only C's standard I/O header, to ensure the previous save/file will be safe should the program crash while overwriting it, that doesn't leave behind temporary files?
A similar idea incorporating post's comments:
@PC Luddite @Thomas Padron-McCarthy @Martin James
The central issue is that either A) a gap in time exist between having a valid "state" file or B) a small interval exists with 2 valid files. So a worst case failure ends with 0 files using A and 2 files using B. Clearly B is preferable.
Writing the state Assume code could crash just before, during, or just after any step except #1.
State.txt
.State_tmp1.txt
. To know this completed, some check code should be part of the "state". This step could be combined with the previous step as an over-write.State_tmp1.txt
to State_tmp2.txt
to verify some aspects of code having rename privileges.State.txt
to State_tmp3.txt
. This is the critical step. Up to now, any failure is inconsequential as State.txt
exist. Until the next step is complete, no State.txt
may exist, yet at least 1 tmp file exist.State_tmp1.txt
to State.txt
. (or from State_tmp2.txt
if step 4 used.)Reading the state.
State.txt
, if found and valid (Passes validity check), proceed to step 3.