Skip to content

Instantly share code, notes, and snippets.

@zparnold
Created September 25, 2020 17:26
Show Gist options
  • Save zparnold/bb3ad34d0bc513315dc9f66d31972af1 to your computer and use it in GitHub Desktop.
Save zparnold/bb3ad34d0bc513315dc9f66d31972af1 to your computer and use it in GitHub Desktop.
You can use this to count all the lines in a directory
package main
import (
"bytes"
"fmt"
"io"
"log"
"math/big"
"os"
"path/filepath"
"runtime"
)
func main() {
var filePath string
//Should support huge numbers
lineCount := big.NewInt(0)
if len(os.Args) <= 1 {
fmt.Println("Need a directory to count. Ex: ./counter ./dir")
os.Exit(-1)
}
filePath = os.Args[1]
err := filepath.Walk(filePath,
func(path string, info os.FileInfo, err error) error {
fmt.Println("Visiting: "+ path)
if err != nil {
return err
}
f, err := os.Open(path)
if err != nil {
return err
}
i, err := lineCounter(f)
lineCount = lineCount.Add(lineCount, big.NewInt(int64(i)))
return nil
})
if err != nil {
log.Println(err)
}
fmt.Println("Total Lines: "+ lineCount.String())
}
func lineCounter(r io.Reader) (int, error) {
buf := make([]byte, 32*1024)
count := 0
var lineSep []byte
if runtime.GOOS == "windows"{
lineSep = []byte{'\r','\n'}
} else {
lineSep = []byte{'\n'}
}
for {
c, err := r.Read(buf)
count += bytes.Count(buf[:c], lineSep)
switch {
case err == io.EOF:
return count, nil
case err != nil:
return count, err
}
}
}
@zparnold
Copy link
Author

To compile (windows):

go build -o counter.exe

To compile (non-windows):

go build -o counter

To use (windows):

.\counter.exe .\dir

To use (non-windows):

./counter ./dir

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment