File: ioutil.go

package info (click to toggle)
golang-github-siddontang-go 0.0~git20170517.0.cb568a3-4
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 484 kB
  • sloc: makefile: 3
file content (39 lines) | stat: -rw-r--r-- 851 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 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.

package ioutil2

import (
	"io"
	"io/ioutil"
	"os"
	"path"
)

// Write file to temp and atomically move when everything else succeeds.
func WriteFileAtomic(filename string, data []byte, perm os.FileMode) error {
	dir, name := path.Dir(filename), path.Base(filename) 
	f, err := ioutil.TempFile(dir, name)
	if err != nil {
		return err
	}
	n, err := f.Write(data)
	f.Close()
	if err == nil && n < len(data) {
		err = io.ErrShortWrite
	} else {
		err = os.Chmod(f.Name(), perm)
	}
	if err != nil {
		os.Remove(f.Name())
		return err
	}
	return os.Rename(f.Name(), filename)
}

// Check file exists or not
func FileExists(name string) bool {
	_, err := os.Stat(name)
	return !os.IsNotExist(err)
}