Factor out atomic file overwriting into its own function.