forked from torbiak/gopl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
54 lines (50 loc) · 1.1 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// ex1.4 prints the count and text of lines that appear more than once in the
// input. It reads from stdin or from a list of named files.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
counts := make(map[string]int)
foundIn := make(map[string][]string)
files := os.Args[1:]
if len(files) == 0 {
countLines(os.Stdin, counts, foundIn)
} 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, foundIn)
f.Close()
}
}
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%v\t%s\n", n, foundIn[line], line)
}
}
}
func in(needle string, strings []string) bool {
for _, s := range strings {
if needle == s {
return true
}
}
return false
}
func countLines(f *os.File, counts map[string]int, foundIn map[string][]string) {
input := bufio.NewScanner(f)
for input.Scan() {
line := input.Text()
counts[line]++
if !in(f.Name(), foundIn[line]) {
foundIn[line] = append(foundIn[line], f.Name())
}
}
// NOTE: ignoring potential errors from input.Err()
}