Golang-Folder Traversal

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

folder Traversal can be used filepath.Walk(root string, walkFn filepath.WalkFunc) error to implement, very convenient, root can be 文件夹的绝对路径 or can be 文件的绝对路径 , but usually used 文件夹 , for the 文件 purpose, traversal is meaningless.

New filetraversalFolder.go

// traversalFolder.gopackage mainimport (    "fmt"    "os"    "path/filepath")func walkFunc(path string, info os.FileInfo, err error) error {    if info == nil {        // 文件名称超过限定长度等其他问题也会导致info == nil        // 如果此时return err 就会显示找不到路径,并停止查找。        println("can't find:(" + path + ")")        return nil    }    if info.IsDir() {        println("This is folder:(" + path + ")")        return nil    } else {        println("This is file:(" + path + ")")        return nil    }}func showFileList(root string) {    err := filepath.Walk(root, walkFunc)    if err != nil {        fmt.Printf("filepath.Walk() error: %v\n", err)    }    return}

In main.go , you can call the

// FileRW project main.gopackage mainimport (    "fmt")func main() {    var path string    fmt.Println("请输入想要遍历的路径:")    fmt.Scanf("%s", &path)    fmt.Println("=====")    // path = "D:\\精通windows server 2008 R2.pdf"    showFileList(path)}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.