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
+9.9k CodeIgniter : Load different view for mobile devices
+11.4k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+6k Golang : Measure execution time for a function
+4.3k Linux/MacOSX : Search and delete files by extension
+6.9k Golang : How to setup a disk space used monitoring service with Telegram bot
+9k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+10.2k Golang : cannot assign type int to value (type uint8) in range error
+16.4k Golang : File path independent of Operating System
+6.5k Golang : Convert an executable file into []byte example
+4.8k Javascript : How to get width and height of a div?
+19k Golang : Check whether a network interface is up on your machine
+11.5k CodeIgniter : Import Linkedin data