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
+4.4k Golang : If else example and common mistake
+18.2k Golang : Close channel after ticker stopped example
+16.5k Golang : Convert IPv4 address to decimal number(base 10) or integer
+3.4k Javascript : How to show different content with noscript?
+4.7k Linux : Disable and enable IPv4 forwarding
+4.7k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+8.1k Golang : How to get garbage collection data?
+6.9k Golang : Add build version and other information in executables
+20.5k Golang : How to reverse slice or array elements order
+8k Random number generation with crypto/rand in Go
+6.9k Swift : Convert (cast) String to Float