Compare commits
1 Commits
Author | SHA1 | Date |
---|---|---|
Stephen McQuay | 0052da8e97 |
|
@ -0,0 +1,51 @@
|
|||
// 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()
|
||||
}
|
Loading…
Reference in New Issue