-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileoperation.go
79 lines (67 loc) · 1.19 KB
/
fileoperation.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"fmt"
"io"
"os"
)
var path = "~/dev/git/gists/file"
func main() {
createFile()
writeFile()
readFile()
deleteFile()
}
func createFile() {
// detect if file exists
var _, err = os.Stat(path)
// create file if not exists
if os.IsNotExist(err) {
var file, err = os.Create(path)
checkError(err)
defer file.Close()
}
}
func writeFile() {
// open file using READ & WRITE permission
var file, err = os.OpenFile(path, os.O_RDWR, 0644)
checkError(err)
defer file.Close()
// write some text to file
_, err = file.WriteString("halo\n")
checkError(err)
_, err = file.WriteString("mari belajar golang\n")
checkError(err)
// save changes
err = file.Sync()
checkError(err)
}
func readFile() {
// re-open file
var file, err = os.OpenFile(path, os.O_RDWR, 0644)
checkError(err)
defer file.Close()
// read file
var text = make([]byte, 1024)
for {
n, err := file.Read(text)
if err != io.EOF {
checkError(err)
}
if n == 0 {
break
}
}
fmt.Println(string(text))
checkError(err)
}
func deleteFile() {
// delete file
var err = os.Remove(path)
checkError(err)
}
func checkError(err error) {
if err != nil {
fmt.Println(err.Error())
os.Exit(0)
}
}