forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.go
86 lines (73 loc) · 1.44 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
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
80
81
82
83
84
85
86
package filex
import (
"io"
"os"
)
const bufSize = 1024
// FirstLine returns the first line of the file.
func FirstLine(filename string) (string, error) {
file, err := os.Open(filename)
if err != nil {
return "", err
}
defer file.Close()
return firstLine(file)
}
// LastLine returns the last line of the file.
func LastLine(filename string) (string, error) {
file, err := os.Open(filename)
if err != nil {
return "", err
}
defer file.Close()
return lastLine(filename, file)
}
func firstLine(file *os.File) (string, error) {
var first []byte
var offset int64
for {
buf := make([]byte, bufSize)
n, err := file.ReadAt(buf, offset)
if err != nil && err != io.EOF {
return "", err
}
for i := 0; i < n; i++ {
if buf[i] == '\n' {
return string(append(first, buf[:i]...)), nil
}
}
first = append(first, buf[:n]...)
offset += bufSize
}
}
func lastLine(filename string, file *os.File) (string, error) {
info, err := os.Stat(filename)
if err != nil {
return "", err
}
var last []byte
offset := info.Size()
for {
offset -= bufSize
if offset < 0 {
offset = 0
}
buf := make([]byte, bufSize)
n, err := file.ReadAt(buf, offset)
if err != nil && err != io.EOF {
return "", err
}
if buf[n-1] == '\n' {
buf = buf[:n-1]
n--
} else {
buf = buf[:n]
}
for n--; n >= 0; n-- {
if buf[n] == '\n' {
return string(append(buf[n+1:], last...)), nil
}
}
last = append(buf, last...)
}
}