-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.go
50 lines (46 loc) · 1.03 KB
/
file.go
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
40
41
42
43
44
45
46
47
48
49
50
package debug
import (
"fmt"
"os"
"path/filepath"
)
// FileSave Save string to file. Create file if not exist and append file if exist. If file name is not specified, create file name is the same program name and .txt at extension
func FileSave(body []byte, file, path string) (err error) {
const ext string = `.txt`
var (
fileName string
fh *os.File
pi os.FileInfo
)
if path, err = os.Getwd(); err != nil {
return
}
if path != "" {
pi, err = os.Stat(path)
if err != nil && os.IsNotExist(err) == false {
return
}
if err == nil {
err = os.MkdirAll(path, 0755)
if err != nil {
return
}
}
if pi.IsDir() == false {
err = fmt.Errorf("incorrect specified path %q is a file", path)
return
}
}
if file == "" {
file = filepath.Base(os.Args[0]) + ext
}
fileName = path + string(os.PathSeparator) + file
if fh, err = os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644); err != nil {
return
}
if _, err = fh.Write(body); err != nil {
return
}
err = fh.Close()
return
}