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
+12.4k Golang : List running EC2 instances and descriptions
+14.9k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+6.3k Golang & Javascript : How to save cropped image to file on server
+11.2k Golang : Fix go.exe is not compatible with the version of Windows you're running
+6.6k Golang : Calculate diameter, circumference, area, sphere surface and volume
+10.3k Golang : Bcrypting password
+51.5k Golang : Check if item is in slice/array
+51.4k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+11.8k Golang : Convert(cast) float to int
+5.5k Unix/Linux : How to archive and compress entire directory ?
+52.8k Golang : How to get struct field and value by name
+10.4k Golang : Embed secret text string into binary(executable) file