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
+19.1k Golang : Check if directory exist and create if does not exist
+9.3k Golang : Terminate-stay-resident or daemonize your program?
+5.4k Golang : Stop goroutine without channel
+8.7k Golang : Heap sort example
+22.4k Golang : How to read JPG(JPEG), GIF and PNG files ?
+5.5k PHP : Fix Call to undefined function curl_init() error
+15.5k Golang : How to convert(cast) IP address to string?
+5.9k AWS S3 : Prevent Hotlinking policy
+51.3k Golang : Check if item is in slice/array
+23.6k Find and replace a character in a string in Go
+9.4k Facebook : Getting the friends list with PHP return JSON format
+10.3k Golang : Generate random integer or float number