go递归遍历文件目录
package main
import (
"fmt"
"io/ioutil"
"log"
)
//文件目录树形结构节点
type dirTreeNode struct {
name string
child []dirTreeNode
}
//递归遍历文件目录
func getDirTree(pathName string) (dirTreeNode, error) {
rd, err := ioutil.ReadDir(pathName)
if err != nil {
log.Fatalf("Read dir '%s' failed: %v", pathName, err)
}
var tree, childNode dirTreeNode
tree.name = pathName
var name, fullName string
for _, fileDir := range rd {
name = fileDir.Name()
fullName = pathName + "/" + name
if fileDir.IsDir() {
childNode, err = getDirTree(fullName)
if err != nil {
log.Fatalf("Read dir '%s' failed: %v", fullName, err)
}
} else {
childNode.name = name
childNode.child = nil
}
tree.child = append(tree.child, childNode)
}
return tree, nil
}
//递归打印文件目录
func printDirTree(tree dirTreeNode, prefix string) {
fmt.Println(prefix + tree.name)
if len(tree.child) > 0 {
prefix += "----"
for _, childNode := range tree.child {
printDirTree(childNode, prefix)
}
}
}
func main() {
dirName := "D:/go/src/jet"
tree, err := getDirTree(dirName)
if err != nil {
log.Fatalln("read dir '%s' fail: %v", dirName, err)
}
printDirTree(tree, "")
}
如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!
txttool.com 说一段 esp56物联 查询128 IP查询