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
+14.4k Golang : Fix image: unknown format error
+22.9k Golang : Set and Get HTTP request headers example
+32k Golang : Get local IP and MAC address
+13k Golang : flag provided but not defined error
+7.5k Golang : How to iterate a slice without using for loop?
+7.5k Golang : How to fix html/template : "somefile" is undefined error?
+29.8k Golang : Saving(serializing) and reading file with GOB
+17.9k Golang : [json: cannot unmarshal object into Go value of type]
+14.2k Golang : Reverse IP address for reverse DNS lookup example
+26.8k Golang : Encrypt and decrypt data with AES crypto
+20.1k Golang : Measure http.Get() execution time
+4.5k Linux/MacOSX : Search and delete files by extension