1 // Copyright 2015 The etcd Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package ioutil 16 17 import ( 18 "io" 19 "os" 20 21 "go.etcd.io/etcd/client/pkg/v3/fileutil" 22 ) 23 24 // WriteAndSyncFile behaves just like ioutil.WriteFile in the standard library, 25 // but calls Sync before closing the file. WriteAndSyncFile guarantees the data 26 // is synced if there is no error returned. 27 func WriteAndSyncFile(filename string, data []byte, perm os.FileMode) error { 28 f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) 29 if err != nil { 30 return err 31 } 32 n, err := f.Write(data) 33 if err == nil && n < len(data) { 34 err = io.ErrShortWrite 35 } 36 if err == nil { 37 err = fileutil.Fsync(f) 38 } 39 if err1 := f.Close(); err == nil { 40 err = err1 41 } 42 return err 43 } 44