util.go 675 B

12345678910111213141516171819202122232425262728293031
  1. package raft
  2. import (
  3. "io"
  4. "os"
  5. )
  6. // WriteFile writes data to a file named by filename.
  7. // If the file does not exist, WriteFile creates it with permissions perm;
  8. // otherwise WriteFile truncates it before writing.
  9. // This is copied from ioutil.WriteFile with the addition of a Sync call to
  10. // ensure the data reaches the disk.
  11. func writeFileSynced(filename string, data []byte, perm os.FileMode) error {
  12. f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
  13. if err != nil {
  14. return err
  15. }
  16. n, err := f.Write(data)
  17. if n < len(data) {
  18. f.Close()
  19. return io.ErrShortWrite
  20. }
  21. err = f.Sync()
  22. if err != nil {
  23. return err
  24. }
  25. return f.Close()
  26. }