Go: how to list the files of a directory

Go: how to list the files of a directory

In this article we will see how to get the list of files in a directory with Go.

Listing the files contained in a directory is a very common operation. In this article we will see how to get the list of files in a directory with Go.

Go allows us to carry out this operation via the os package which has the Readdir() function which can be obtained via the handle of the directory opened for reading.

We thus obtain a slice of the elements contained in the directory. Each object has the functions to determine whether we are processing a file or a directory and to obtain the name of the current file from the filesystem.

package main

import (
     "fmt"
     "os"
)

func listFiles(dir string) ([]string, error) {
	listing := []string{}
	f, err := os.Open(dir)
	if err != nil {
	    return listing, err
	}
	files, err := f.Readdir(0)
	if err != nil {
	    return listing, err
	}
	for _, file := range files {
	    if !file.IsDir() {
	        fName := file.Name()
                listing = append(listing, fName)
            }
        }
        return listing, nil
}

func main() {
     files, err := listFiles('./test');
     if err != nil {
         panic(err)
     }
     fmt.Println(files)
}

The listFiles function takes the directory path as a parameter and returns a slice containing the file names and a possible error if the directory is not accessible for reading.