代码:

按行写文件

1
2
3
4
5
6
7
8
f, err := os.OpenFile(fileName,
os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
if err != nil {
return
}
w := bufio.NewWriter(f)
fmt.Fprintln(w, fmt.Sprintf("start analysis log at the %s \r\n", `"`+logFileDir+`"`))
w.Flush()

按行读文件

1
2
3
4
5
6
7
8
9
10
11
buf := bufio.NewReader(file)
for {
line, err := buf.ReadString('\n')
line = strings.TrimSpace(line)
if err != nil {
if err == io.EOF { //读取结束,会报EOF
return nil
}
return err
}
}