Golang : Read directory content with os.Open
There are few ways to traverse a directory tree and content in Go. One of them is os.File.Readdir function. In this tutorial, we will see how to read a directory and display its files and size. This example will use the os.Open http://golang.org/pkg/os/#File.Readdir function.
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
dirname := "." + string(filepath.Separator)
d, err := os.Open(dirname)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer d.Close()
files, err := d.Readdir(-1)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Reading "+ dirname)
for _, file := range files {
if file.Mode().IsRegular() {
fmt.Println(file.Name(), file.Size(), "bytes")
}
}
}
Test this code out and see the output of your directory. Hope this tutorial is helpful.
See also : Golang : Read directory content with filepath.Walk()
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
+6.5k Golang : Map within a map example
+10.5k Golang : How to delete element(data) from map ?
+25.6k Golang : How to write CSV data to file
+4.7k JavaScript: Add marker function on Google Map
+4.7k Unix/Linux : How to pipe/save output of a command to file?
+11k Golang : Create S3 bucket with official aws-sdk-go package
+7.4k Golang : Rot13 and Rot5 algorithms example
+8.6k Golang : How to join strings?
+8.3k Your page has meta tags in the body instead of the head
+19.3k Golang : Fix cannot download, $GOPATH not set error
+17.6k Golang : Defer function inside init()
+14.4k Golang : Find network of an IP address