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
+11.9k Golang : Convert a rune to unicode style string \u
+9.9k Golang : Channels and buffered channels examples
+50.9k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+10.5k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+14.1k Golang : Check if a file exist or not
+6k Golang : Measure execution time for a function
+26.6k Golang : How to check if a connection to database is still alive ?
+19.2k Golang : Execute shell command
+6.5k Golang : Convert an executable file into []byte example
+9.3k Golang : Generate EAN barcode
+9.8k Golang : Get current, epoch time and display by year, month and day
+14.3k Golang : Recombine chunked files example