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
+10.2k Golang : Resolve domain name to IP4 and IP6 addresses.
+9k Golang : How to get ECDSA curve and parameters data?
+10.7k Golang : Fix go.exe is not compatible with the version of Windows you're running
+19.5k Golang : Append content to a file
+5.5k Unix/Linux : Get reboot history or check when was the last reboot date
+34.9k Golang : Integer is between a range
+10.3k Golang : ISO8601 Duration Parser example
+6.2k Golang : Handling image beyond OpenCV video capture boundary
+12.6k Golang : Get terminal width and height example
+15k Golang : Get query string value on a POST request
+6.3k Elasticsearch : Shutdown a local node
+9.4k Golang : Sort and reverse sort a slice of floats