5

[Go] 递归获取目录下的文件

 2 years ago
source link: https://studygolang.com/articles/35290
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

[Go] 递归获取目录下的文件

jefferyjob · 1天之前 · 83 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览    

操作示例:

./scan /Document/dir

代码:

// 定义递归文件树结构体
type treeList struct {
    Path string `json:"path"`
    File     []string  `json:"file"`
    Children []*treeList `json:"children"`
}

func main() {
    // 获取命令行输入的参数
    var dir string
    arg_num := len(os.Args)
    if arg_num < 2 {
        fmt.Println("Waring:请输入路径的名称")
        return
    }
    dir = os.Args[1] + "/"

    // 初始化tree结构体
    treelist := new(treeList)

    // 递归文件目录下的所有文件
    recursion(dir, treelist)

    // 将递归结构体转为json
    bytes, _ := json.Marshal(treelist)
    // fmt.Printf("%s",bytes)
    fmt.Println(string(bytes))
}

// 递归函数
func recursion(dir string, treelist *treeList) *treeList {
    // 读取文件夹下的所有文件
    files, err := ioutil.ReadDir(dir)
    if err != nil {
        fmt.Printf("Dir(%s) scan error,err:%v\n", dir, err)
    }

    // 定义存放文件的切片
    var fileSlice []string

    // 得到文件名次或文件夹名次
    for _, f := range files {
        filename := f.Name()
        if f.IsDir() { // 如果是文件夹,则继续递归
            fpath := dir + filename + "/"
            children := recursion(fpath,new(treeList))
            treelist.Children = append(treelist.Children,children)
        } else{ // 如果是文件
            fileSlice = append(fileSlice,filename)
        }
    }

    // 写入查找路径路径
    treelist.Path = dir

    // 当前目录的文件给到 treelist.File
    treelist.File = fileSlice

    return treelist
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK