How to save files?

Published on July 14, 2008

How to save files?

    Suppose there is a file, for example, a config.
    You need to read it, change some value, and write it down again.
    It would seem that could be easier?

    Performing code audits for various teams, I noticed that in almost every project, file saving is done incorrectly. And for me it was a revelation that for the vast majority of even good programmers, this knowledge was closed ... In order not to repeat it many times, I want to share this secret knowledge. By the way, this applies to all programming languages.

    1. Create a temporary file , while processing all possible exceptional situations.
    2. You write to this temporary file , while also processing all possible exceptional situations when recording.
    3. Close the temporary file , and remember that when closing, there may also be exceptional situations (since flush buffers and a number of operations in the file system are done).
    4. If everything is okay in the previous steps, rename the temporary file, giving it the name of the existing file , while the old file is deleted, and the temporary file replaces it. In this case, you also need to intercept and handle all possible exceptional situations.

    Steps 1-3 can be combined into one step if a special function or method is used to create and save the entire file in one operation.

    If you don’t do this, then the smallest problem such as lack of disk space can lead to data loss (for example, if there is no disk space, then during normal recording to a file, a file of zero length will be directly created in place of the old one, and further recording will not be performed) . And there are a lot of such problems, for example, the computer may reboot during the save process, in this case, the recording will also not be performed, and the file will be corrupted, etc.