In this article, we will see how to list the directories, subdirectories and files recursively.

Here, we use thefilepath.Walk function to recursively traverse a directory and its subdirectories to list all the directories, subdirectories, and files efficiently.

Following is the example of how to achieve this:

package main

import (
    "fmt"
    "os"
    "path/filepath"
)

func main() {
    root := "." // the root directory to start listing from

    // Define a function to handle each file or directory encountered during the walk
    walkFunc := func(path string, info os.FileInfo, err error) error {
        if err != nil {
            fmt.Printf("Error accessing %q: %v\n", path, err)
            return err
        }
        if info.IsDir() {
            fmt.Printf("Directory: %s\n", path)
        } else {
            fmt.Printf("File: %s\n", path)
        }
        return nil
    }

    // Traverse the directory tree from the root, calling walkFunc for each file or directory
    err := filepath.Walk(root, walkFunc)
    if err != nil {
        fmt.Printf("Error walking the path %q: %v\n", root, err)
        return
    }
}

Explanation:

In the above example, we define a root directory to start listing from, and a walkFunc function that is called for each file or directory encountered during the walk. The walkFunc function prints the path to each directory or file.

The filepath.Walk is then called using the arguments root and walkFunc, the walk function will walk through the directory tree, calling walkFunc for each file and directory along the way.

We use the info.IsDir() to check if the current item is the directory or a file and take the action appropriately.

This technique’s speed is enhanced by its use of a depth-first search to navigate the filesystem directory structure. It also offers a clear and concise method of displaying a directory tree’s complete file and folder listings.

Categorized in:

Tagged in: