The usual recipe is to write to a temporary file in the same directory and then rename it over the target. On POSIX filesystems a rename within one filesystem replaces the name in one step.