pkg.re/essentialkaos/ek.10@v12.41.0+incompatible/fsutil/line_count.go (about) 1 package fsutil 2 3 // ////////////////////////////////////////////////////////////////////////////////// // 4 // // 5 // Copyright (c) 2022 ESSENTIAL KAOS // 6 // Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0> // 7 // // 8 // ////////////////////////////////////////////////////////////////////////////////// // 9 10 import ( 11 "bytes" 12 "errors" 13 "io" 14 "os" 15 ) 16 17 // ////////////////////////////////////////////////////////////////////////////////// // 18 19 // CountLines returns number of lines in given file 20 func CountLines(file string) (int, error) { 21 if file == "" { 22 return 0, errors.New("Path to file is empty") 23 } 24 25 fd, err := os.OpenFile(file, os.O_RDONLY, 0) 26 27 if err != nil { 28 return 0, err 29 } 30 31 // Use 32k buffer 32 buf := make([]byte, 32*1024) 33 count, sep := 0, []byte{'\n'} 34 35 for { 36 c, err := fd.Read(buf) 37 38 if err != nil && err != io.EOF { 39 fd.Close() 40 return 0, err 41 } 42 43 count += bytes.Count(buf[:c], sep) 44 45 if err == io.EOF { 46 break 47 } 48 } 49 50 return count, fd.Close() 51 }