登录
首页 >  Golang >  Go问答

在Golang中如何限制filepath.walk()函数的目录递归深度?

来源:stackoverflow

时间:2024-03-05 22:09:25 444浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《在Golang中如何限制filepath.walk()函数的目录递归深度?》,聊聊,我们一起来看看吧!

问题内容

我想在包含各种子目录的目录中搜索特定类型的文件。我在 Golang 中使用 filepath.walk() 来实现此目的。但是,我不想递归迭代超出我知道该文件不能存在的最大深度。

Golang中有这样的预建函数/库吗?


正确答案


首先,你应该使用go 1.16中引入的filepath.WalkDir,它比filepath.walk更高效。

walk 的效率低于 go 1.16 中引入的 walkdir,它避免了对每个访问的文件或目录调用 os.lstat。

然后,无法将最大深度指定为直接参数。您必须计算 walkdirfunc 中的递归深度。

显然,计算文件路径中的分隔符是 acceptable strategy(并且可以说比其他可能的技巧更简单),因此解决方案可能如下所示:

maxdepth := 2
    rootdir := "root"
    err := filepath.walkdir(rootdir, func(path string, d fs.direntry, err error) error {
        if err != nil {
            // handle possible path err, just in case...
            return err
        }
        if d.isdir() && strings.count(path, string(os.pathseparator)) > maxdepth {
            fmt.println("skip", path)
            return fs.skipdir
        }
        // ... process entry
        return nil
    })

所以目录结构如下:

.
└── root
    ├── a.txt
    ├── b.txt
    └── root1
        ├── a.txt
        └── root2
            ├── a.txt
            ├── b.txt
            ├── root3
            │   └── a.txt
            └── root4

假设root位于深度0,上面的代码打印:

skip root/root1/root2/root3
skip root/root1/root2/root4
func ControlDeepWalk(basepath string, count int, hard, debug bool) error {
    var (
        stock       = make(map[string][]string)
        countBase   = 0
        correctdirs []string
    )
    base := filepath.Base(basepath)
    dirbase := filepath.Dir(basepath)
    countBase = len(strings.Split(filepath.Dir(basepath), "/"))
    if debug {
        log.Printf("countbase: %v  %v\n", strings.Split(filepath.Dir(basepath), "/"), countBase)
        log.Printf("base :%v : %v : %v\n", base, dirbase, strings.Split(basepath, "/"))
    }

    err := filepath.WalkDir(basepath, func(path string, d fs.DirEntry, err error) error {
        if err != nil {
            if debug {
                log.Printf("--error inf walkdir function, exit")
            }
            return err
        }
        if d.IsDir() {
            if filepath.Dir(path) == filepath.Dir(basepath) {
                if debug {
                    log.Printf("found root directory, skipping  %v :  %v\n", filepath.Dir(path), filepath.Dir(basepath))
                }
            } else {
                compare := false
                if hard {
                    compare = len(strings.Split(filepath.Dir(path), "/")) == countBase+count
                } else {
                    compare = len(strings.Split(filepath.Dir(path), "/")) <= countBase+count
                }
                if compare {
                    if debug {
                        log.Printf("-found dir: [%v] %v\n", path, d.Name())
                    }
                    stock[filepath.Dir(filepath.Join(path, d.Name()))] = []string{}
                    correctdirs = append(correctdirs, filepath.Dir(filepath.Join(path, d.Name())))
                }
            }
        } else {
            fdir, ffile := filepath.Split(path)
            for _, x := range correctdirs {
                if x == filepath.Dir(fdir) {
                    if debug {
                        log.Printf("-found file:%v  : %v   %v  %v \n", d.Name(), path, fdir, ffile)
                    }
                    stock[x] = append(stock[x], d.Name())
                }
            }
        }
        return nil
    })
    if debug {
        for k, v := range stock {
            log.Printf("%v : %v \n", k, v)
        }
        log.Printf("%v\n", stock)
    }
    return err
}



func main() {
    p := "/backup/backuper/test"
    count := 2
    _ = ControlDeepWalk(p, count, false, true)

}

享受吧,伙计! :)

今天关于《在Golang中如何限制filepath.walk()函数的目录递归深度?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>