mirror of
https://github.com/zeromicro/go-zero.git
synced 2026-05-13 18:00:00 +08:00
fix: handle with read the empty file (#4258)
This commit is contained in:
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user