-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLnReader.go
68 lines (60 loc) · 1.12 KB
/
LnReader.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
/**
LnReader 文件行阅读器
2018年7月10日 星期二
*/
package xini
import (
"bufio"
"errors"
"os"
)
// LnReader the lines of file reader
type LnReader struct {
Filename string // 文件名
error
}
func NewLnRer(filename string) *LnReader {
return &LnReader{
Filename: filename,
}
}
// Scan file lines
func (ln *LnReader) Scan(callback func(line string)) bool {
fs, err := os.Open(ln.Filename)
if err != nil {
ln.error = err
return false
}
buf := bufio.NewReader(fs)
for {
line, err2 := buf.ReadString('\n')
callback(line)
// 错误
if err2 != nil {
break
}
}
return true
}
// ScanWithFlInfo file lines
func (ln *LnReader) ScanWithFlInfo(callback func(line string)) (os.FileInfo, error) {
fs, err := os.Open(ln.Filename)
if err != nil {
return nil, errors.Join(errors.New("文件读取失败"), err)
}
defer fs.Close()
buf := bufio.NewReader(fs)
for {
line, err2 := buf.ReadString('\n')
callback(line)
// 错误
if err2 != nil {
break
}
}
stat, err := fs.Stat()
if err != nil {
return nil, errors.Join(errors.New("获取文件信息错误"), err)
}
return stat, nil
}