Writes to a temp file and then replaces (delete+rename) the target file, so that it always contains complete and valid contents.