Let's assume your file is data.xml
. Instead of writing to data.xml
all the time, write to a temporary file data.xml.tmp
, and when finished, rename it to data.xml
. But renaming will not work if you already have a data.xml
file, so you will need to delete it first and then rename the temporary file.
That way, data.xml
will contain the last safe data. If you have a sudden shutdown, the incomplete file will be the temporary data.xml.tmp
. If your program tries to read the file later on and there is no data.xml
file, that means the shutdown happened between the delete and rename operations, so you will have to read the temporary file instead. We know it is safe because otherwise there would be a data.xml
file.