Golang file Traversal

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

Package Main

Import (
"FMT"
"Io/ioutil"
"OS"
"Path/filepath"
"Strings"
)

Gets all the files under the specified directory, does not go to the next level of directory search, can match the suffix filter.
Func Listdir (dirpth string, suffix string) (files []string, err Error) {
Files = Make ([]string, 0, 10)

Dir, err: = Ioutil. ReadDir (dirpth)
If err! = Nil {
return nil, err
}

PTHSEP: = string (OS. PathSeparator)
suffix = strings. ToUpper (suffix)//ignore suffix matching case

For _, Fi: = Range dir {
If Fi. Isdir () {//Ignore directory
Continue
}
If strings. Hassuffix (Strings. ToUpper (FI. Name ()), suffix) {//matching file
Files = append (files, Dirpth+pthsep+fi. Name ())
}
}

return files, nil
}

Gets all files under the specified directory and all subdirectories, and can match suffix filtering.
Func walkdir (dirpth, suffix string) (files []string, err Error) {
Files = Make ([]string, 0, 30)
suffix = strings. ToUpper (suffix)//ignore suffix matching case

Err = filepath. Walk (Dirpth, func (filename string, fi os. FileInfo, err Error) error {//traverse directory
If err! = Nil {//Ignore error
return err
//}

If Fi. Isdir () {//Ignore directory
return Nil
}

If strings. Hassuffix (Strings. ToUpper (FI. Name ()), suffix) {
Files = append (files, filename)
}

return Nil
})

return files, err
}

Func Main () {
Files, err: = Listdir ("D:\\go", ". txt")
Fmt. Println (Files, err)

files, err = Walkdir ("E:\\study", ". pdf")
Fmt. Println (Files, err)
}

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.