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.9k Golang : Get all countries phone codes
+4.7k Linux/Unix/PHP : Restart PHP-FPM
+3.7k Linux : sudo yum updates not working
+17.3k Golang : Padding data for encryption and un-padding data for decryption
+8.2k Golang : Scramble and unscramble text message by randomly replacing words
+19.8k Golang : For loop continue,break and range
+5.1k Javascript : Get operating system and browser information
+15.8k Golang : XML to JSON example
+35.1k Golang : Convert date or time stamp from string to time.Time type
+14.1k Golang : Get query string value on a POST request
+11.2k Golang : How to check if a string starts or ends with certain characters or words?
+16.1k Golang : When to use init() function?