I am developing a document-based desktop application that writes a rather large and complex file to disk when the user saves his document. What is the best practice to prevent data corruption? There are several things that can happen:
The save process may fail halfway, which, of course, is a serious application error, but in this case it is better to leave the old file than a damaged half-written file. The same problem will occur if the application is terminated for any other reason halfway through the file entry.
The most reliable approach I can come up with is to use a temporary file when saving and replace only the original file after successfully creating a new file. But I find that there are several operations (creating tempfile, saving to tempfile, deleting the original, moving tempfile to the original), which may or may not be unsuccessful, and I get a rather complicated mess of try / catch statements to handle them correctly.
Is there a best practice / standard for this scenario? For example, is it better to copy the original to a temp file and then overwrite the original than save it in a temporary file?
Also, what is the reason for the state of the file in the document-based application (in windows)? Is it better to leave the file open for writing in the application until the user closes the document, or simply closes in the open file and closes it again? Pros and cons?
source share