You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
42 lines
598 B
Go
42 lines
598 B
Go
package iox
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"io"
|
|
"os"
|
|
)
|
|
|
|
const bufSize = 32 * 1024
|
|
|
|
// CountLines returns the number of lines in the file.
|
|
func CountLines(file string) (int, error) {
|
|
f, err := os.Open(file)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
defer f.Close()
|
|
|
|
var noEol bool
|
|
buf := make([]byte, bufSize)
|
|
count := 0
|
|
lineSep := []byte{'\n'}
|
|
|
|
for {
|
|
c, err := f.Read(buf)
|
|
count += bytes.Count(buf[:c], lineSep)
|
|
|
|
switch {
|
|
case errors.Is(err, io.EOF):
|
|
if noEol {
|
|
count++
|
|
}
|
|
return count, nil
|
|
case err != nil:
|
|
return count, err
|
|
}
|
|
|
|
noEol = c > 0 && buf[c-1] != '\n'
|
|
}
|
|
}
|