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.4k Golang : Test input string for unicode example
+28.6k Golang : Change a file last modified date and time
+12.4k Golang : How to check if a string starts or ends with certain characters or words?
+5.8k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+11k Golang : Replace a parameter's value inside a configuration file example
+15.8k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+11.2k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+14.5k Golang : Rename directory
+14k Golang : concatenate(combine) strings
+22k Golang : Use TLS version 1.2 and enforce server security configuration over client
+11.5k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+12.9k Golang : http.Get example