finish_writing_to_file_impl() should remove temporary file if replacing an existing one failed

Functions like start_writing_to_file() rely on finish_writing_to_file_impl() to remove the temporary file if replacing an already existing one failed.

Currently this doesn't happen. The attached patch fixes this.