github.com/lingyao2333/mo-zero@v1.4.1/core/iox/textfile.go (about)

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