// Chapter 32 example: a word counter that reads files, or standard input in a pipe. // Run with: go run exercises/32/07-wc.go exercises/31/poem.txt // Or pipe: Get-Content exercises/31/poem.txt | go run exercises/32/07-wc.go // Build: go build -o wc.exe exercises/32/07-wc.go package main import ( "bufio" "flag" "fmt" "os" "strings" "unicode/utf8" ) type counts struct { lines int words int chars int } // count reads f line by line. Characters are counted without the line endings. func count(f *os.File) (counts, error) { var c counts scanner := bufio.NewScanner(f) for scanner.Scan() { line := scanner.Text() c.lines++ c.words += len(strings.Fields(line)) c.chars += utf8.RuneCountInString(line) } return c, scanner.Err() } func countFile(name string) (counts, error) { f, err := os.Open(name) if err != nil { return counts{}, err } defer f.Close() return count(f) } func usage() { fmt.Fprintln(os.Stderr, "usage: wc [FILE...]") fmt.Fprintln(os.Stderr, "Counts lines, words and characters. With no FILE, reads standard input.") } func main() { flag.Usage = usage flag.Parse() if flag.NArg() == 0 { c, err := count(os.Stdin) if err != nil { fmt.Fprintln(os.Stderr, "wc:", err) os.Exit(1) } fmt.Printf("%6d %6d %6d\n", c.lines, c.words, c.chars) return } exitCode := 0 for _, name := range flag.Args() { c, err := countFile(name) if err != nil { fmt.Fprintln(os.Stderr, "wc:", err) exitCode = 1 continue } fmt.Printf("%6d %6d %6d %s\n", c.lines, c.words, c.chars, name) } os.Exit(exitCode) }