Menu Close

Go – How to list all files and folders in a directory in go

Here, We will see how to list all files and folders in a directory in go. We can do it by using ReadDir() function in ioutil package in go golang.

Function prototype:

func ReadDir(dirname string) ([]os.FileInfo, error)

dirname : directory name

ReadDir() reads the directory named by dirname and returns a list of directory entries sorted by filename.

Return value:

ReadDir() function in ioutil package returns 
a list of directory entries sorted by filename.

Example with code:

package main

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

func main() {

  dir_path := "/Users/"

  files, err := ioutil.ReadDir(dir_path)

  if err != nil {

    log.Fatal(err)

  }

  for _, file := range files {

    fmt.Println(file.Name())
  }

}

Output:

$ sudo go run sample.go

.localized
Shared
john
hello.go

To learn more about golang, Please refer given below link:

https://techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, ioutil, packages

Leave a Reply

Your email address will not be published. Required fields are marked *