title: Overwriting a file without the risk of a corrupt file
body: <p>So often my applications want to save files to load again later. Having recently got unlucky with a crash, I want to write the operation in such a way that I am guaranteed to either have the new data, or the original data, but no a corrupted mess.</p>
  
  <p>My first idea was to do something along the lines of (to save a file called example.dat):</p>
  
  <ol>
  <li>Come up with a unique file name for the target directory, e.g. example.dat.tmp</li>
  <li>Create that file and write my data to it.</li>
  <li>Delete the original file (example.dat)</li>
  <li>Rename ("Move") the temp file to where the original was (example.dat.tmp -> example.dat).</li>
  </ol>
  
  <p>Then at load time the application can follow the following rules:</p>
  
  <ul>
  <li>If no "example.dat" and no  "example.dat.tmp", first run / new project, so load in the defaults / create new file.</li>
  <li>If "example.dat" and no "example.dat.tmp", then load example.dat (normal load case)</li>
  <li>If "example.dat.tmp" exists offer the user the chance to potentially recover data. If "example.dat" also exists, do not overwrite it without explicit user constant.</li>
  </ul>
  
  <p>However, having done a little research, I found that as well as OS caching which I may be able to override with the file flush methods, some disk drives still then cache internally and may even lie to the OS saying they are done, so 4. could complete, the write is not actually written, and if the system goes down I have lost my data...</p>
  
  <p>I am not sure the disk problem is actually solvable by an application, but are the general rules above the correct thing to do? Should I keep an old recovery copy of the file for longer to be sure, what are the guidelines regarding such things (e.g. acceptable disk usage, should the user choose, where to put such files, etc.).</p>
  
  <p>Also how should I avoid potential conflict the user and other programs for "example.dat.tmp". I recall seeing a "~example.dat" sometimes from some other software, is that a better convention?</p>