textfile.go 575 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package iox
  2. import (
  3. "bytes"
  4. "io"
  5. "os"
  6. )
  7. const bufSize = 32 * 1024
  8. // CountLines returns the number of lines in file.
  9. func CountLines(file string) (int, error) {
  10. f, err := os.Open(file)
  11. if err != nil {
  12. return 0, err
  13. }
  14. defer f.Close()
  15. var noEol bool
  16. buf := make([]byte, bufSize)
  17. count := 0
  18. lineSep := []byte{'\n'}
  19. for {
  20. c, err := f.Read(buf)
  21. count += bytes.Count(buf[:c], lineSep)
  22. switch {
  23. case err == io.EOF:
  24. if noEol {
  25. count++
  26. }
  27. return count, nil
  28. case err != nil:
  29. return count, err
  30. }
  31. noEol = c > 0 && buf[c-1] != '\n'
  32. }
  33. }