Golang Program to get the list the name of files in a specified directory


In Golang, we have two internal functions - ReadDir() and Walk function to get a list of filenames prenent in a specific directory. Here we have write three examples. In the first example We will use the ReadDir() function present in ioutil package while in the second one we are using the walk function present in the filepath package.

Method 1: Using ioutil PACKAGE

The ioutil package in Golang provides several functions to perform input/Output operations, including reading the files and directories. The ReadDir() function of the ioutil package is used to get the list of files in a specified directory.

Syntax

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

The ReadDir() function takes the directory name as an argument and returns a slice of os.FileInfo and an error if any. The os.FileInfo interface provides information about a file or directory, including its name, size, and timestamps.

Algorithm

  • Import the ioutil package in your Go program.

  • Call the ioutil.ReadDir() function, passing the path to the directory as an argument.

  • The ReadDir() function returns a slice of os.FileInfo objects, each representing a file or directory in the specified directory.

  • Loop through the slice of os.FileInfo objects and print the names of the files.

Example

In this example, we are going to use ioutil package of Golang to get the list the name of files in a specified directory

package main
import (
   "fmt"
   "io/ioutil"
)
 
func main() {
   files, err := ioutil.ReadDir(".")
   if err != nil {
      fmt.Println("Error:", err)
      return
   }
   for _, file := range files {
      fmt.Println(file.Name())
   }
}

Output

.cache
main.go

Method 2: Using OS PACKAGE

The os package in Golang provides several functions to perform operating system operations, including reading the files and directories. The Readdir() function of the os package is used to get the list of files in a specified directory.

Syntax

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

The Readdir() function takes the directory name as an argument and returns a slice of os.FileInfo and an error if any.

Algorithm

  • Import the fmt and os package in your Go program.

  • Call the os.Open() function, passing the path to the directory as an argument.

  • The Open() function returns a pointer to an os.File object, which represents the opened directory.

  • Call the Readdir() function on the os.File object, which returns a slice of os.FileInfo objects, each representing a file or directory in the specified directory.

  • Loop through the slice of os.FileInfo objects and print the names of the files.

Example

In this example, we used the os.Open() function to open the current directory (denoted by "."), and the os.File.Readdir() method to get the list of files. The returned slice of os.FileInfo is then looped through, and the Name() method of each os.FileInfo is used to print the file names.

package main
import (
   "fmt"
   "os"
)

func main() {
   dir, err := os.Open(".")
   if err != nil {
      fmt.Println("Error:", err)
      return
   }
   defer dir.Close()
   files, err := dir.Readdir(-1)
   if err != nil {
      fmt.Println("Error:", err)
      return
   }
   for _, file := range files {
      fmt.Println(file.Name())
   }
}

Output

.cache
main.go

Method 3: Using Filepath Package

The filepath package in Golang provides several functions to perform operations related to file paths, including reading the files and directories. The Walk() function of the filepath package is used to get the list of files in a specified directory.

Syntax

func Walk(root string, walkFn WalkFunc) error

The Walk() function takes the root directory name and a callback function (WalkFunc) as arguments. The WalkFunc function is called for each file or directory in the tree rooted at root, including root itself. The error return value of the WalkFunc is propagated back up the call chain.

Algorithm

  • Import the filepath and fmt packages in your Go program.

  • Define a callback function of type filepath.WalkFunc, which is called for each file or directory in the tree rooted at root, including root itself.

  • Call the filepath.Walk() function, passing the root directory name and the callback function as arguments.

  • The Walk() function traverses the tree rooted at root, calling the callback function for each file or directory in the tree.

  • In the callback function, print the names of the files, if they are not directories.

  • The error return value of the WalkFunc is propagated back up the call chain. Check for any error that may occur during the Walk() function.

Example

In this example, we used the filepath.Walk() function to traverse the current directory (denoted by "."). The callback function is called for each file and directory in the tree, and only the names of the files are printed.

package main
import (
   "fmt"
   "path/filepath"
   "os"
)
 
func main() {
   err := filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
      if !info.IsDir() {
         fmt.Println(info.Name())
      }
      return nil
   })
   if err != nil {
      fmt.Println("Error:", err)
      return
   }
}

Output

0e2b514f755ee4f625d64cbbd7c2105ede7801c584c4b7c84ab92a6bba8bead3-a
488f59492c5d2acb89df6f7dd4adeb489e794f4c7f4b7099b1ce8bfd4bb76555-d
491a6fde5177b15e27e5483d63c5275ef3fb4d1160e2f0250593f0500e3ffa42-d
README
c1e4b74d07dece466552274a8aaf6ea8cbe8b38326ab63779edc68c311125873-a
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855-d
ef52495a5cadbbe9f3a90c71303222f26f455e79cdb1e4a5bd23c6d0fd037dfa-a
f93942f3d6be608e81b2d3c28c3ed57f5c78c1367b8844742d977252fc2921e2-a
main.go

Conclusion

In Conclusion, Golang provides several methods to get the list of file names in a specified directory, including using the ioutil package, os package, and filepath package. Each method has its own syntax, use case, and algorithm, and the choice of method depends on the requirements of the specific task. Whether you need to perform a simple directory listing or traverse the entire directory tree, Golang has the necessary tools to accomplish the task efficiently and effectively.

Updated on: 22-Feb-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements