How to List Files in a Directory in Go

1. Introduction

Listing files in a directory is a common requirement in many software applications. In Go, the os package provides functions that make it simple to read the contents of a directory. This blog post will explain how to list the files in a directory using Go.

2. Program Steps

1. Use os.ReadDir to read the directory contents.

2. Iterate over the returned slice to access information about each entry.

3. Handle any errors that may occur while reading the directory.

3. Code Program

To list files in Go, you can use the os.ReadDir or the ioutil.ReadDir function, which returns a slice of os.DirEntry or os.FileInfo objects, respectively. These objects contain information about each file or directory within the specified directory.

Here is the complete Go program to demonstrate how to list files in a directory:
package main

import (
	"fmt"
	"os"
)

func main() {
	// Directory to list files from
	dirPath := "."

	// Step 1: Use os.ReadDir to read the directory contents
	entries, err := os.ReadDir(dirPath)
	if err != nil {
		fmt.Println("Error reading directory:", err)
		return
	}

	// Step 2: Iterate over the slice of directory entries
	fmt.Println("Files in directory:", dirPath)
	for _, entry := range entries {
		// Step 3: Handle the entries and print the file names
		fmt.Println("-", entry.Name())
	}
}

Output:

Files in directory: .
- file1.txt
- file2.go
- some_directory

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" and import "os" - Importing the necessary packages for formatted output and operating system functionality.

3. dirPath is the path to the directory from which the files will be listed. Here, it's set to ".", the current directory.

4. os.ReadDir is called with dirPath to obtain a list of directory entries.

5. If os.ReadDir returns an error, it is printed, and the function exits early.

6. If no error occurs, a for loop iterates over the slice of os.DirEntry objects, printing the name of each with entry.Name().

7. The output displays the list of files and directories in the specified dirPath. Actual file and directory names will vary based on the contents of the current directory where the Go program is executed.


Comments