Go: List all files and folders in a directory

Use the ioutil.ReadDir function in package io/ioutil. It returns a sorted slice containing elements of type os.FileInfo.

The code in this example prints a sorted list of all file names in the current directory:

files, err := ioutil.ReadDir(".")
if err != nil {
        log.Fatal(err)
}
for _, f := range files {
        fmt.Println(f.Name())
}

Example output:

dev
etc
tmp
usr

Comments

Be the first to comment!