Skip to content

Instantly share code, notes, and snippets.

@dyoo
Created July 24, 2013 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dyoo/6074547 to your computer and use it in GitHub Desktop.
Save dyoo/6074547 to your computer and use it in GitHub Desktop.
Playing around with more go stuff; line counting utility
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
)
func main() {
for _, filename := range os.Args[1:] {
// Check if we're a directory or not.
fileInfo, err := os.Stat(filename)
if err != nil {
log.Fatal(err)
}
if fileInfo.IsDir() {
fmt.Println(filename, " DIRECTORY")
continue
}
// Read contents of file, watch for newline bytes
f, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
reader := bufio.NewReader(f)
lineCount := 0
for {
nextByte, err := reader.ReadByte()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
if nextByte == '\n' {
lineCount++
}
}
fmt.Println(filename, lineCount)
err = f.Close()
if err != nil {
log.Fatal(err)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment