ioutil.go 850 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. // Copyright 2012, Google Inc. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package ioutil2
  5. import (
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "path"
  10. )
  11. // Write file to temp and atomically move when everything else succeeds.
  12. func WriteFileAtomic(filename string, data []byte, perm os.FileMode) error {
  13. dir, name := path.Dir(filename), path.Base(filename)
  14. f, err := ioutil.TempFile(dir, name)
  15. if err != nil {
  16. return err
  17. }
  18. n, err := f.Write(data)
  19. f.Close()
  20. if err == nil && n < len(data) {
  21. err = io.ErrShortWrite
  22. } else {
  23. err = os.Chmod(f.Name(), perm)
  24. }
  25. if err != nil {
  26. os.Remove(f.Name())
  27. return err
  28. }
  29. return os.Rename(f.Name(), filename)
  30. }
  31. // Check file exists or not
  32. func FileExists(name string) bool {
  33. _, err := os.Stat(name)
  34. return !os.IsNotExist(err)
  35. }