Created
September 25, 2020 17:26
-
-
Save zparnold/bb3ad34d0bc513315dc9f66d31972af1 to your computer and use it in GitHub Desktop.
You can use this to count all the lines in a directory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To compile (windows):
To compile (non-windows):
To use (windows):
To use (non-windows):