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
+29k Golang : Save map/struct to JSON or XML file
+4.4k Javascript : Access JSON data example
+11.6k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+9.9k Golang : Use regular expression to get all upper case or lower case characters example
+24.7k Golang : Generate MD5 checksum of a file
+14k Golang : Recombine chunked files example
+22.6k Golang : Test file read write permission example
+5.4k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+5k Golang : Print instead of building pyramids
+22.6k Golang : Calculate time different
+5.3k Golang : Display advertisement images or strings on random order
+5.9k Linux/Unix : Commands that you need to be careful about