fix: handle with read the empty file (#4258)

This commit is contained in:
JiChen
2024-07-20 22:01:13 +10:00
committed by GitHub
parent cf5b080fbe
commit 9de04ee035
2 changed files with 62 additions and 3 deletions

View File

@@ -35,6 +35,7 @@ func firstLine(file *os.File) (string, error) {
for {
buf := make([]byte, bufSize)
n, err := file.ReadAt(buf, offset)
if err != nil && err != io.EOF {
return "", err
}
@@ -45,6 +46,10 @@ func firstLine(file *os.File) (string, error) {
}
}
if err == io.EOF {
return string(append(first, buf[:n]...)), nil
}
first = append(first, buf[:n]...)
offset += bufSize
}
@@ -56,25 +61,34 @@ func lastLine(filename string, file *os.File) (string, error) {
return "", err
}
bf := int64(bufSize)
var last []byte
offset := info.Size()
for {
offset -= bufSize
if offset < 0 {
if offset < bufSize {
bf = offset
offset = 0
} else {
offset -= bf
}
buf := make([]byte, bufSize)
buf := make([]byte, bf)
n, err := file.ReadAt(buf, offset)
if err != nil && err != io.EOF {
return "", err
}
if n == 0 {
return "", nil
}
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
@@ -82,5 +96,9 @@ func lastLine(filename string, file *os.File) (string, error) {
}
last = append(buf, last...)
if offset == 0 {
return string(last), nil
}
}
}