c++ - Adequetely safe method of overwriting a save file? -


using cstdio, safest way of overwriting file? 'safe' in case meaning there's no chance file become incomplete or corrupted; file either overwritten, or old file should have gone awry.

i imagine best way this, create temporary intermediate file, overwrite old file once intermediate complete. if best way though, there's few other problems that'd seem possible, if albeit rare.

  • how know use other file should program quit while overwriting?
  • how know not use other file should program quit during it's creation?
  • how know original file or intermediate in undefined state (since may fail in way remains readable data contains subtly wrong)?

i imagine there's single practice this, haven't been able find it. saved game data; there's 1 file, , entire file overwritten every time well, there no partial overwrites or appending worry about.

as others have said, keep existing file around, , write fresh file. if it's important (that is, user can't possibly recover information), make sure there "backup" file around (e.g. if program saves abc.config, leave abc.old.config or abc.backup [if want guarantees name works everywhere, .cfg , .bak may better choices]).

when write file, put sort of endmarker in file, can sure file complete. if want avoid "user editing" of file, may want have checksum of content (sha1, md5 or similar). if endmarker isn't there, or checksum wrong, know file "bad", don't use it. go backup.

  1. write new conten temporary file (eg. fstream fout("abc.tmp");)
  2. delete backup file (if exists) (e.g remove("abc.bak");)
  3. rename old file backup name (e.g. rename("abc.cfg", "abc.bak");)
  4. rename new file old 1 (e.g. rename("abc.tmp", "abc.cfg");

for steps (in particular writing actual data), check errors. need decide ok errors , not (remove of file doesn't exist ok, example, if rename doesn't work should stop, or may end bad).

when loading file, check steps, if goes wrong, go backup file.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -