An official microsoft recommendation on how to ensure that a file, representing a particular state, is written in a consistent way is to write it into a temporary file and ReplaceFile it.
But if we'll assume a bit more higher-level task - a change to the state represented in the file - it becomes a bit more problematic.
To make a change to a state within a file, you need to read the state from the file, make the change and write it back. While the "writing" portion we may consider be covered by the ReplaceFile function, the fact that the file could have been changed since we've read it is not.
In other words, we may need to check if the file is still the same and has not updated since, before the ReplaceFile call. If we are about talking text editors here - a modification time check before the call should be enough. But if we want something a bit more robust - we should acknowledge the possibility of file changing after the modification time check, but before the call.
The naive approach would be to implement a CompareAndReplaceFile call, that will lock the original file, check that it's the same file, then replicating what ReplaceFile does. Nor only this is a bit hacky solution (copy-pasting logic of a system function is not a good practice), but it also implies a longer lock period.
For instance, on Linux, the same effect could be achieved by utilizing fcntl(2)'s (FD_SETLEASE) file leasing to have a chance of aborting your operation once someone else opens a file for writing, prior to rename(2), which is atomic and does not open a file, so you can keep a lease through it.
Are there ways to implement a transactional file change on Windows, aside of a hacky solution discussed above?