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
+28.7k Golang : Calculate percentage change of two values
+23k Golang : Time slice or date sort and reverse sort example
+12.7k Golang: Pad right or print ending(suffix) zero or spaces in fmt.Printf example
+6.2k Golang : Process json data with Jason package
+9.6k PHP : Convert(cast) bigInt to string
+11.3k Swift : Convert (cast) Int or int32 value to CGFloat
+6.8k Golang : get the current working directory of a running program
+4.3k Golang : Return multiple values from function
+16.3k Golang : Aligning strings to right, left and center with fill example
+11.3k Golang : Covert map/slice/array to JSON or XML format
+18.4k Golang : How to count the number of repeated characters in a string?
+14.4k Golang : How to reverse elements order in map ?