其他分享
首页 > 其他分享> > 递归遍历文件目录

递归遍历文件目录

作者:互联网

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, "")
}

  

标签:dirTreeNode,遍历,文件目录,递归,err,tree,child,childNode,name
来源: https://www.cnblogs.com/wujuntian/p/11635879.html