go-zero/core/filex/file.go

104 lines
1.6 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package filex
import (
"io"
"os"
)
const bufSize = 1024
2021-02-19 14:30:38 +08:00
// FirstLine returns the first line of the file.
2020-07-26 17:09:05 +08:00
func FirstLine(filename string) (string, error) {
file, err := os.Open(filename)
if err != nil {
return "", err
}
defer file.Close()
return firstLine(file)
}
2021-02-19 14:30:38 +08:00
// LastLine returns the last line of the file.
2020-07-26 17:09:05 +08:00
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)
2020-07-26 17:09:05 +08:00
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
}
}
if err == io.EOF {
return string(append(first, buf[:n]...)), nil
}
2020-07-26 17:09:05 +08:00
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
2024-07-20 22:44:13 +08:00
bufLen := int64(bufSize)
2020-07-26 17:09:05 +08:00
offset := info.Size()
2024-07-20 22:44:13 +08:00
for offset > 0 {
if offset < bufLen {
bufLen = offset
2020-07-26 17:09:05 +08:00
offset = 0
} else {
2024-07-20 22:44:13 +08:00
offset -= bufLen
2020-07-26 17:09:05 +08:00
}
2024-07-20 22:44:13 +08:00
buf := make([]byte, bufLen)
2020-07-26 17:09:05 +08:00
n, err := file.ReadAt(buf, offset)
if err != nil && err != io.EOF {
return "", err
}
if n == 0 {
2024-07-20 22:44:13 +08:00
break
}
2020-07-26 17:09:05 +08:00
if buf[n-1] == '\n' {
buf = buf[:n-1]
2021-02-19 14:30:38 +08:00
n--
2020-07-26 17:09:05 +08:00
} else {
buf = buf[:n]
}
2024-07-20 22:44:13 +08:00
for i := n - 1; i >= 0; i-- {
if buf[i] == '\n' {
return string(append(buf[i+1:], last...)), nil
2020-07-26 17:09:05 +08:00
}
}
last = append(buf, last...)
}
2024-07-20 22:44:13 +08:00
return string(last), nil
2020-07-26 17:09:05 +08:00
}