1 package main 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "os" 7 "path/filepath" 8 "strings" 9 )10 11 var matchCount = 012 var ch = make(chan int, 512)13 14 func findFile(path string, text string) {15 var pathArray [100]string16 var count = 017 filepath.Walk(path, func(path string, info os.FileInfo, err error) error {18 if err != nil {19 }20 //find text21 if !info.IsDir() {22 if info.Size() < 1024*1024 {23 pathArray[count] = path24 count++25 if count >= 100 {26 count = 027 go findText(pathArray[0:100], text)28 <-ch29 }30 }31 }32 return nil33 })34 go findText(pathArray[0:count], text)35 <-ch36 37 fmt.Printf("一共发现了 %d 个匹配的文件", matchCount)38 39 }40 41 func findText(paths []string, text string) {42 for _, path := range paths {43 fi, err := os.Open(path)44 if err != nil {45 panic(err)46 }47 defer fi.Close()48 fd, err := ioutil.ReadAll(fi)49 if err != nil {50 panic(err)51 }52 53 if strings.Index(string(fd), text) > -1 {54 matchCount++55 fmt.Println(path)56 }57 }58 ch <- 159 }60 61 func main() {62 args := os.Args63 if len(args) < 3 {64 fmt.Println("需要两个参数 path text")65 return66 }67 path := args[1]68 text := args[2]69 70 _, err := os.Stat(path)71 72 if err != nil {73 fmt.Println("path不存在")74 } else {75 findFile(path, text)76 }77 }
计数器增加的时候应该加锁