In Go, listing all files and subfolders within a given directory can be achieved using the standard library. This tutorial will demonstrate how to accomplish this task efficiently.
Using the filepath package
The filepath package provides utilities for manipulating filename paths. To list files and directories, we can use the Walk function of the filepath package.
package main
import (
"fmt"
"log"
"os"
"path/filepath"
)
func main() {
root := "./your_directory_path"
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
log.Println(err)
return err
}
fmt.Println(path)
return nil
})
if err != nil {
log.Fatal(err)
}
}Replace "./your_directory_path" with the actual path of the directory you want to inspect. This code will traverse every file and directory starting from the specified root, printing out each path.
Explanation of the Walk Function
The filepath.Walk function takes two arguments:
- root: The root directory from which to start walking.
- walkFn: A callback function that's called for every file or directory in the tree.
The walkFn takes three parameters:
- path: The current path being visited.
- info: An os.FileInfo object that contains information about the file or directory.
- err: Any error encountered during the walking process.
If your callback handles an error and wishes to stop further processing, returning the error will abort the walk.
Using os and ioutil packages
Alternatively, you can use a combination of the os and io/ioutil packages for manual directory walking:
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
)
func ListDir(dir string) {
files, err := ioutil.ReadDir(dir)
if err != nil {
log.Fatal(err)
}
for _, file := range files {
fmt.Println(filepath.Join(dir, file.Name()))
if file.IsDir() {
ListDir(filepath.Join(dir, file.Name()))
}
}
}
func main() {
ListDir("./your_directory_path")
}This recursive function lists all files and directories by reading the directory content using ioutil.ReadDir, and then recursively calling itself for every subdirectory.
Conclusion
Listing files and directories in Go can be easily achieved using the built-in filepath or os and io/ioutil packages. Depending on your preference for usage and efficiency, you can choose either approach to implement directory listing in your Go applications.