Golang递归查找目录中指定的文件

package main

import (
    "fmt"
    "io/ioutil"
)

var matches int

func main() {
    matches := search1("./test", "data.txt")
    fmt.Println("matches:", matches)
    
}

func search1(path, queryName string) int {
    files, err := ioutil.ReadDir(path)
    fmt.Println("files-------:", files)
    if err != nil {
        fmt.Println("目录读取失败!", err.Error())
        return matches
    }   
    if len(files) <= 0 {
        return matches 
    }   
    for _, file := range files {
        name := file.Name()
        fmt.Println("name-----:", name)
        if name == queryName {
            matches++
        }   
        if file.IsDir() {
            dir := path + "/" + name
            if path == "/" {
                dir = path + name
            }   
            search1(dir, queryName)
        }   
    }   
    return matches
}   

你可能感兴趣的:(Golang递归查找目录中指定的文件)