go语言扫描目录

作者: ljh123 | 来源:发表于2018-10-07 19:50 被阅读11次
    package main
    
    import (
        "io/ioutil"
        "log"
        "os"
        "fmt"
    )
    
    func main() {
        files := scanDir("C:\\")
        for _, file := range files {
            fmt.Println(file)
        }
    }
    
    
    // 扫描当前目录下文件,不递归扫描
    func scanDir(dirName string) []string {
        files, err := ioutil.ReadDir(dirName)
        if err != nil {
            log.Println(err)
        }
        var fileList []string
        for _, file := range files {
            fileList = append(fileList, dirName + string(os.PathSeparator) + file.Name())
        }
        return fileList
    }
    
    // 递归扫描目录
    func scanDirs(dirName string) []string {
        files, err := ioutil.ReadDir(dirName)
        if err != nil {
            log.Println(err)
        }
        var fileList []string
        for _, file := range files {
            fileList = append(fileList, dirName + string(os.PathSeparator) + file.Name())
            if file.IsDir() {
                fileList = append(fileList, scanDir(dirName + string(os.PathSeparator) + file.Name())...)
            }
        }
        return fileList
    }
    

    相关文章

      网友评论

        本文标题:go语言扫描目录

        本文链接:https://www.haomeiwen.com/subject/qgcraftx.html