To recursively walk through a directory and its subdirectories using the os
package in Golang, you can use the filepath.Walk
function. Here's an example:
package main
import (
"fmt"
"os"
"path/filepath"
)
func visit(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// You can perform actions on each visited file or directory here
fmt.Println(path)
return nil
}
func main() {
root := "." // Change the root directory as per your requirement
err := filepath.Walk(root, visit)
if err != nil {
fmt.Printf("Error walking the path %s: %v\n", root, err)
}
}
In this example, the visit
function is called for each visited file or directory. It receives the path, file info, and any error that occurred during the visit.
You can perform any desired actions on each visited file or directory within the visit
function. In this example, it simply prints the path of each visited item.
Make sure to update the root
variable to specify the directory you want to start the recursive walk from.