-
Notifications
You must be signed in to change notification settings - Fork 0
/
readwrite_file.go
54 lines (46 loc) · 954 Bytes
/
readwrite_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
51
52
53
54
package service
import (
"bufio"
"fmt"
"os"
)
// AppendLine append lines to file
func AppendLine(line, path string) error {
file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer file.Close()
if _, err = file.WriteString(line); err != nil {
return err
}
return nil
}
// ReadLine read file line by line
func ReadLine(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
lines = append(lines, line)
}
return lines, scanner.Err()
}
// WriteLine write file line by line
func WriteLine(lines []string, path string) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
w := bufio.NewWriter(file)
for _, line := range lines {
fmt.Fprintln(w, line)
}
return w.Flush()
}