In Golang, I am looking for an efficient way to determine the number of lines a file has.
Of course, I can always loop through the entire file, but does not seem ver
There is no approach that is significantly faster than yours as there is no meta-data on how many lines a file has. You could reach a little speed up by manually looking for newline-characters:
func lineCount(r io.Reader) (int n, error err) {
buf := make([]byte, 8192)
for {
c, err := r.Read(buf)
if err != nil {
if err == io.EOF && c == 0 {
break
} else {
return
}
}
for _, b := range buf[:c] {
if b == '\n' {
n++
}
}
}
if err == io.EOF {
err = nil
}
}