Debian Codegraph @

ioutil2/ioutil.go

raw
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
5 package ioutil2
6
7 import (
8 "io"
9 "io/ioutil"
10 "os"
11 "path"
12 )
13
14 // Write file to temp and atomically move when everything else succeeds.
15 func WriteFileAtomic(filename string, data []byte, perm os.FileMode) error {
16 dir, name := path.Dir(filename), path.Base(filename)
17 f, err := ioutil.TempFile(dir, name)
18 if err != nil {
19 return err
20 }
21 n, err := f.Write(data)
22 f.Close()
23 if err == nil && n < len(data) {
24 err = io.ErrShortWrite
25 } else {
26 err = os.Chmod(f.Name(), perm)
27 }
28 if err != nil {
29 os.Remove(f.Name())
30 return err
31 }
32 return os.Rename(f.Name(), filename)
33 }
34
35 // Check file exists or not
36 func FileExists(name string) bool {
37 _, err := os.Stat(name)
38 return !os.IsNotExist(err)
39 }