dup2.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Dup2 prints the count and text of lines that appear more than once
  2. // in the input. It reads from stdin or from a list of named files.
  3. package main
  4. import (
  5. "bufio"
  6. "fmt"
  7. "os"
  8. )
  9. func Test() {
  10. fmt.Printf("test message!")
  11. }
  12. func DUP2() {
  13. counts := make(map[string]int)
  14. files := os.Args[1:]
  15. for _,value := range files {
  16. f,err :=os.Open(value)
  17. fmt.Printf("内容:%s\n",value)
  18. fmt.Print(f,err) // 地址
  19. }
  20. if len(files) == 0 {
  21. countLines(os.Stdin, counts)
  22. } else {
  23. for _, arg := range files {
  24. f, err := os.Open(arg)
  25. if err != nil {
  26. fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
  27. continue
  28. }
  29. countLines(f, counts)
  30. f.Close()
  31. }
  32. }
  33. for line, n := range counts {
  34. fmt.Printf("%d\t%s\n", n, line)
  35. }
  36. }
  37. //这里是读的文件内容
  38. func countLines(f *os.File, counts map[string]int) {
  39. input := bufio.NewScanner(f)
  40. for input.Scan() && input.Text() != "end!" { //读取file的输入.--todo:这里的读取过程,会报错么,该怎么改
  41. counts[input.Text()]++
  42. }
  43. // NOTE: ignoring potential errors from input.Err()
  44. }