52 lines
976 B
Go
52 lines
976 B
Go
// ex1.4 solves exercise 1.4
|
|
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"os"
|
|
)
|
|
|
|
func main() {
|
|
counts := make(map[string]int)
|
|
files := make(map[string]map[string]bool)
|
|
inputs := os.Args[1:]
|
|
if len(inputs) == 0 {
|
|
countLines(os.Stdin, counts, files)
|
|
} else {
|
|
for _, arg := range inputs {
|
|
f, err := os.Open(arg)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "ex1.4: %v\n", err)
|
|
continue
|
|
}
|
|
if err := countLines(f, counts, files); err != nil {
|
|
panic(err)
|
|
}
|
|
f.Close()
|
|
}
|
|
}
|
|
for line, n := range counts {
|
|
if n > 1 {
|
|
fmt.Printf("%d\t%q\n", n, line)
|
|
for file := range files[line] {
|
|
fmt.Printf("\tin %q\n", file)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func countLines(f *os.File, counts map[string]int, files map[string]map[string]bool) error {
|
|
input := bufio.NewScanner(f)
|
|
for input.Scan() {
|
|
line := input.Text()
|
|
counts[line]++
|
|
|
|
if _, ok := files[line]; !ok {
|
|
files[line] = make(map[string]bool)
|
|
}
|
|
files[line][f.Name()] = true
|
|
}
|
|
return input.Err()
|
|
}
|