Skip to content

Instantly share code, notes, and snippets.

@Hubro
Created February 17, 2017 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Hubro/76e6b7c906c308b84b23188578b74483 to your computer and use it in GitHub Desktop.
Save Hubro/76e6b7c906c308b84b23188578b74483 to your computer and use it in GitHub Desktop.
Line counter written in Go
package main
import (
"bytes"
"fmt"
"io"
"os"
)
func main() {
args := os.Args[1:]
if len(args) != 1 {
fmt.Fprintln(os.Stderr, "Expected 1 argument: File path")
os.Exit(1)
}
path := args[0]
file, err := os.Open(path)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to open file: %v", err)
os.Exit(1)
}
count, err := lineCounter(file)
if err != nil {
fmt.Fprintf(os.Stderr, "Encountered error while counting: %v", err)
os.Exit(1)
}
fmt.Println(count)
}
func lineCounter(r io.Reader) (int, error) {
buf := make([]byte, 32*1024)
count := 0
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
}
}
}
@Hubro
Copy link
Author

Hubro commented Feb 17, 2017

func lineCounter taken from this stackoverflow.com answer: http://stackoverflow.com/a/24563853/388916

@dacastill0-zz
Copy link

dacastill0-zz commented Oct 29, 2018

@Hubro Could I enter in this comparison the function I did to count lines?
In my comparison my function is at least four times faster than the one you are testing.

https://stackoverflow.com/questions/24562942/golang-how-do-i-determine-the-number-of-lines-in-a-file-efficiently/52153000#52153000

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