Golang : Read directory content with filepath.Walk()
Golang's filepath.Walk function allow a program to traverse a directory content and tree with ease. In this tutorial, we will see how to read a directory and display its content name with file size. This example will use the http://golang.org/pkg/path/filepath/#Walk function.
readdirwalk.go
package main
import (
"path/filepath"
"os"
"flag"
"fmt"
)
func walkpath(path string, f os.FileInfo, err error) error {
fmt.Printf("%s with %d bytes\n", path,f.Size())
return nil
}
func main() {
flag.Parse()
root := flag.Arg(0) // 1st argument is the directory location
filepath.Walk(root, walkpath)
}
execute go run readdirwalk.go ./
and see how it goes. You can change to different directory and test out the output as well. Hope this tutorial is helpful to you.
See also : Golang : Read directory content with os.Open
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+21.3k Golang : How to get time zone and load different time zone?
+12.7k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+14.9k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+23.6k Golang : Check if element exist in map
+18k Golang : Simple client server example
+5.9k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+14.3k Golang : Fix image: unknown format error
+36.1k Golang : Get file last modified date and time
+36.8k Golang : Display float in 2 decimal points and rounding up or down
+5.6k PHP : Fix Call to undefined function curl_init() error
+45.1k Golang : Use wildcard patterns with filepath.Glob() example
+5.6k Golang : Stop goroutine without channel