使用 Golang 实现,修改 dup2 程序。(Go 语言圣经书后习题 1.4)
修改 dup2 ,出现重复的行时打印文件名称。
我们只需要在出现重复行时,打印出来即可。
package main
import (
"bufio"
"fmt"
"os"
)
type LnFile struct {
Count int
Filenames []string
}
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
counts := make(map[string]*LnFile)
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)
}
countLines(f, counts)
f.Close()
}
}
for line, n := range counts {
if n.Count > 1 {
fmt.Printf("%d %v\n%s\n", n.Count, n.Filenames, line)
}
}
}
func countLines(f *os.File, counts map[string]*LnFile) {
input := bufio.NewScanner(f)
for input.Scan() {
key := input.Text()
_, ok := counts[key]
if ok {
counts[key].Count++
counts[key].Filenames = append(counts[key].Filenames, f.Name())
} else {
counts[key] = new(LnFile)
counts[key].Count = 1
counts[key].Filenames = append(counts[key].Filenames, f.Name())
}
}
}
我们只需要在出现重复行时,使用 print 打印出来即可。