Skip to content

Instantly share code, notes, and snippets.

@innermond
Created September 14, 2018 20:01
Show Gist options
  • Save innermond/92d43618211a15becc0ba0ff1a499182 to your computer and use it in GitHub Desktop.
Save innermond/92d43618211a15becc0ba0ff1a499182 to your computer and use it in GitHub Desktop.
the other way of reading last line
func readLastLine(f *os.File) (string, error) {
sz, err := f.Seek(0, io.SeekEnd)
if err != nil {
return "", err
}
// ensure we avoid eventually last \n
deep := sz - int64(len("\n")+1)
buf := make([]byte, 1)
// moon walk one byte at time
for {
_, err := f.ReadAt(buf, deep)
if err != nil {
return "", err
}
// find newline position from above
if string(buf) == "\n" {
// we dont need newline above
deep = deep + int64(len("\n"))
break
}
deep--
}
b := make([]byte, sz-deep)
num, err := f.ReadAt(b, deep)
fmt.Printf("deep %d\n", deep)
b = b[:num]
return string(b), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment