This repository has been archived on 2024-08-19. You can view files and clone it, but cannot push or open issues or pull requests.
go-book/dup2/dup2.go
Geir Okkenhaug Jerstad f7443bbab9 init
2024-08-13 20:31:39 +02:00

34 lines
501 B
Go

package main
import (
"bufio"
"fmt"
"os"
)
func main() {
counts := make(map[string]int)
files := os.Args[1:]
if len(files) == 0 {
countLines(os.Stdin, counts)
} else {
for _, arg := range files {
f, err := os.Open(arg)
if err != nil {
fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
continue
}
countLines(f, counts)
f.Close()
}
}
}
func countLines(f *os.File, counts map[string]int) {
input := bufio.NewScanner(f)
for input.Scan() {
counts[input.Text()]++
}
}