Suppose there is any file, for example, a config.
You need to read it, change some value, and write it again.
It would seem, what could be easier?
Performing code auditing for various commands, I noticed that in almost every project, saving files is wrong. And for me it turned out to be a revelation that for the overwhelming majority of even quite good programmers this knowledge turned out to be closed ... In order not to repeat many times, I want to share this intimate knowledge. By the way, this applies to all programming languages.
1.
Create a temporary file , while handling all possible exceptions.
2. You
make a record in this temporary file , and you also handle all possible exceptions while recording.
3.
Close the temporary file , and remember that when closing, there can also be exceptions (as the flush buffer and a number of operations in the file system are done).
4. If in the previous steps everything is in order,
rename the temporary file, giving it the name of an existing file , and the old file will be deleted and the temporary file will replace it. In this case, you also need to intercept and handle all possible exceptions.
')
Steps 1-3 can be combined in one step if you use a special function or method to create and save the entire file, in a single operation.
If you do not do this, then the slightest problem such as insufficient disk space can lead to data loss (for example, if there is no disk space, then a normal write to the file will directly create a zero-length file instead of the old one and no further recording will be made) . And such problems are possible mass, for example, the computer can reboot during the save process, in this case also the recording will not be performed, and the file will be corrupted, etc.