Golang: How do I determine the number of lines in a file efficiently?

后端 未结 3 663
我寻月下人不归
我寻月下人不归 2020-12-04 13:29

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

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 13:50

    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
        }
    }
    

提交回复
热议问题