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
+15k Golang : How to check for empty array string or string?
+5.9k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+6.2k Golang : Create new color from command line parameters
+12k Golang : Convert(cast) bigint to string
+15.8k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+7.5k Golang : How to detect if a sentence ends with a punctuation?
+9.9k Golang : interface - when and where to use examples
+10.3k Golang : Bcrypting password
+5.7k PHP : Convert CSV to JSON with YQL example
+21k Golang : Convert PNG transparent background image to JPG or JPEG image
+10k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral