Skip to content

Instantly share code, notes, and snippets.

@mdmarek
Created October 13, 2015 01:08
Show Gist options
  • Save mdmarek/b35585973b512b7ee168 to your computer and use it in GitHub Desktop.
Save mdmarek/b35585973b512b7ee168 to your computer and use it in GitHub Desktop.
Write a file atomically under Linux.
// Copyright 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Write file to temp and atomically move when everything else succeeds.
func WriteFileAtomic(filename string, data []byte, perm os.FileMode) error {
dir, name := path.Split(filename)
f, err := ioutil.TempFile(dir, name)
if err != nil {
return err
}
_, err = f.Write(data)
if err == nil {
err = f.Sync()
}
if closeErr := f.Close(); err == nil {
err = closeErr
}
if permErr := os.Chmod(f.Name(), perm); err == nil {
err = permErr
}
if err == nil {
err = os.Rename(f.Name(), filename)
}
// Any err should result in full cleanup.
if err != nil {
os.Remove(f.Name())
}
return err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment