So often, my applications want to save files for download later. Having recently received a failure with a crash, I want to write the operation in such a way that I am guaranteed either new data or original data, but not a damaged mess.
My first idea was to do something according to (save a file called example.dat):
- Create a unique file name for the target directory, for example. example.dat.tmp
- Create this file and write me your details.
- Delete source file (example.dat)
- Rename ("Move") the temporary file to where the original was (example.dat.tmp โ example.dat).
Then, at boot time, the application can follow these rules:
- If there is no "example.dat" and no "example.dat.tmp", first run / a new project, so load by default / create a new file.
- If "example.dat" and not "example.dat.tmp", download example.dat (normal download mode)
- If "example.dat.tmp" exists, offer the user the ability to potentially recover data. If "example.dat" also exists, do not overwrite it without an explicit user constant.
However, after doing a little research, I found that just like OS caching, which I can override with file cleaning methods, some disk drives still cache internally and can even lie to the OS saying they are done, so 4. may end, the record is not actually written, and if the system goes down, I lost my data ...
I'm not sure if the disk problem is actually solvable by the application, but are the general rules above the right thing? Should I keep the old copy to restore the file longer, to be sure which rules apply to such things (for example, acceptable disk usage if the user chooses where to put such files, etc.).
Potential conflicts with the user and other programs for "example.dat.tmp" should also be avoided. I remember that sometimes the example โexample.datโ was found from some other software, is this the best agreement?
source share