-
-
Save raypereda/dc44863f50e8a713c9a7b7923cded7d1 to your computer and use it in GitHub Desktop.
Line counter written in Go
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" | |
"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