当前位置:网站首页>Go limit depth traversal of files in directory

Go limit depth traversal of files in directory

2022-04-23 20:41:00 Golang Chinese community

Go offer os.ReadDir、filepath.WalkDir These methods , It is convenient to traverse the files under the specified folder , But it can't well limit the depth of traversing the folder , Here are two ways to implement this function . Method 1: By recursion ```gopackage dirimport ( "os" "path/filepath")// Each file will call back this method type WalkFun func(dir, name string, isDir bool) errorfunc WalkDepth(name string, maxDepth int, fn WalkFun) error { return walkDirs([]string{name}, 1, maxDepth, fn)}// Through each dirs The files under the , And return all dirs The following is the file of the directory func walkDirs(dirs []string, dep, maxDepth int, fn WalkFun) error { var subDirs []string for _, d := range dirs { ff, err := os.ReadDir(d) if err != nil { return err } for _, f := range ff { err = fn(d, f.Name(), f.IsDir()) if err != nil { return err } if f.IsDir() { // If it's a catalog subDirs = append(subDirs, filepath.Join(d, f.Name())) } } } if len(subDirs) > 0 && dep < maxDepth { return walkDirs(subDirs, dep+1, maxDepth, fn) } return nil}``` Method 2: Direct use for Realization ```gopackage dirimport ( "os" "path/filepath")// Each file will call back this method type WalkFun func(dir, name string, isDir bool) errorfunc WalkDepth(name string, maxDepth int, fn WalkFun) error { var ( dep = 0 // depth err error ) dirs := []string{name} // If dirs Next there is dir Or end the cycle when the depth has been exceeded for len(dirs) > 0 && dep != maxDepth { dirs, err = WalkDirs(dirs, fn) // Traverse dirs The files under the , return dirs Files in directory if err != nil { return err } dep++ } return nil}// Through each dirs The files under the , And return all dirs The following is the file of the directory func WalkDirs(dirs []string, fn WalkFun) ([]string, error) { var subDirs []string for _, d := range dirs { ff, err := os.ReadDir(d) if err != nil { return nil, err } for _, f := range ff { err = fn(d, f.Name(), f.IsDir()) if err != nil { return nil, err } if f.IsDir() { // If it's a catalog subDirs = append(subDirs, filepath.Join(d, f.Name())) } } } return subDirs, nil}``` Client calls :```gofunc main() { root := "root" err := dir.WalkDepth(root, 2, func(dir, name string, isDir bool) error { fmt.Println(dir, name, isDir) return nil }) fmt.Println(err)}``` Output results ```root dir-1-1 trueroot dir-1-2 trueroot file-1-3 falseroot/dir-1-1 f11 trueroot/dir-1-2 file-1-2 false``` Traverse root The depth under the directory is 2 Of all the above files and directories , Recursion will be simpler , However, if the recursion depth is too deep, the performance will be affected , So we can evaluate it according to the actual needs . My blog :https://itart.cn/blogs/2022/practice/go-read-dir-limit-depth.html

版权声明
本文为[Golang Chinese community]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204232037297334.html