Skip to content

Instantly share code, notes, and snippets.

@raypereda
Forked from Hubro/main.go
Created November 26, 2018 06:22
Show Gist options
  • Save raypereda/dc44863f50e8a713c9a7b7923cded7d1 to your computer and use it in GitHub Desktop.
Save raypereda/dc44863f50e8a713c9a7b7923cded7d1 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
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment