zoukankan      html  css  js  c++  java
  • 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, "")
    }
    

      

  • 相关阅读:
    弱爆程序员的特征值
    快捷渐变效果
    做事务性的发布数据库日志会越来越大
    判断MS SQLSERVER临时表是否存在
    SQLite实现加密
    CentOS6.4下安装TeamViewer8
    安装CDT
    CentOS中安装Courier New字体
    VS2012的Windows程序不显示DOS窗口
    log4cpp安装使用
  • 原文地址:https://www.cnblogs.com/wujuntian/p/11635879.html
Copyright © 2011-2022 走看看