Go Program to Get Sub Directories List

Go Program to Get Sub Directories List

This Go code is used to read the directory contents like files and sub directory details.

package main

import (
	"fmt"
	"io/ioutil"
)

func main() {

	files, err := ioutil.ReadDir("/etc/java")
	if err == nil {
		for _, file := range files {
			if file.IsDir() {
				fmt.Println(file.Name())
			}
		}
	} else {
		fmt.Println(err.Error())
	}
}

Output:

$ go build directory-list.go 
$ ./directory-list 
security

ReadDir function in ioutil module is to list sub directories and files details.

file.IsDir function is used to check whether file is directory or not.

if directory '/etc/java' is not exists in the system, then this program returns the error message like below.

$ go build directory-info.go 
$ ./directory-list 
open /etc/java1: no such file or directory

How to get symbolic link sub directories ?

If any sub symbolic link directories available inside directory then above code won't work and will not get all the sub directories including symbolic link directories.

To get all the sub directories including symbolic link directories, Following Go code will work,

package main

import (
	"fmt"
	"io/ioutil"
	"os"
)

func main() {

	files, err := ioutil.ReadDir("/sys/class/net/")
	if err == nil {
		for _, file := range files {
			if file.IsDir() || (file.Mode()&os.ModeSymlink == os.ModeSymlink) {
				fmt.Println(file.Name())
			}
		}
	} else {
		fmt.Println(err.Error())
	}
}

Output:

$ go build directory-list.go
$ ./directory-list 
enp0s25
lo
virbr0
virbr0-nic
vnet0
vnet1
wlp3s0