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
+40.8k Golang : Convert []byte to image
+7.2k Golang : Routes multiplexer routing example with regular expression control
+5.8k Golang : Output or print out JSON stream/encoded data
+9.5k Golang : Underscore string example
+9k Golang : Convert octal value to string to deal with leading zero problem
+4.9k nginx : force all pages to be SSL
+4.5k Golang : Detect words using using consecutive letters in a given string
+27.8k Golang : Get first few and last few characters from string
+73.2k Golang : How to return HTTP status code?
+9.1k Android Studio : Simple input textbox and intercept key example
+13k Golang : How to check if your program is running in a terminal
+9.5k Golang : Select region of interest with mouse click and crop from image