Reputation: 413
Wonder if there is a quick way to get a list of files in a root directory that includes the root directory itself.
sourceDir, err := os.Open(startPath)
if err != nil {
return err
}
defer sourceDir.Close()
files, err := sourceDir.Readdir(0)
This only all the files/subdirectorys in "startPath" not "startPath" itself. I have to manually append the fileInfo of startPath to the files manually. Is there a quicker way?
Upvotes: 2
Views: 1883
Reputation: 109339
This is what filepath.Walk
is for.
This will recursively print out every filename:
filepath.Walk(startPath, func(path string, info os.FileInfo, err error) error {
fmt.Println(path)
if err != nil {
fmt.Println("ERROR:", err)
}
return nil
})
Upvotes: 4