Go Program to List Files in a Directory

Introduction

Listing the files in a directory is a common task in file management. In Go, you can achieve this using the os package, which provides functions to read directory contents. This guide will demonstrate how to write a Go program that lists all the files in a specified directory.

Problem Statement

Create a Go program that:

  • Takes the directory path as input.
  • Lists all the files and subdirectories within that directory.
  • Displays the names of the files and directories.

Example:

  • Input: Directory path "./mydir"
  • Output:
    file1.txt
    file2.txt
    subdir1
    subdir2
    

Solution Steps

  1. Import the Necessary Packages: Use import "fmt" and import "os" for file operations and formatted I/O.
  2. Write a Function to List Files in the Directory: Implement a function that reads the directory contents using os.ReadDir.
  3. Write the Main Function: Define the main function, which is the entry point of every Go program.
  4. Prompt the User to Enter the Directory Path: Use fmt.Scanln or fmt.Scanf to take the directory path as input.
  5. Call the Function to List Files in the Directory: Use the function to list the files and subdirectories.
  6. Display the Result: Use fmt.Println to display the names of the files and directories.

Go Program

package main

import (
    "fmt"
    "os"
)

// Step 2: Implement a function to list files in the directory
func listFiles(dirname string) ([]string, error) {
    // Use os.ReadDir to read the directory contents
    entries, err := os.ReadDir(dirname)
    if err != nil {
        return nil, err
    }

    var files []string
    for _, entry := range entries {
        files = append(files, entry.Name())
    }

    return files, nil
}

/**
 * Go Program to List Files in a Directory
 * Author: https://www.javaguides.net/
 */
func main() {
    // Step 4: Prompt the user to enter the directory path
    var dirname string
    fmt.Print("Enter the directory path: ")
    fmt.Scanln(&dirname)

    // Step 5: Call the function to list files in the directory
    files, err := listFiles(dirname)
    if err != nil {
        fmt.Println("Error reading directory:", err)
        return
    }

    // Step 6: Display the result
    fmt.Println("Files and directories in", dirname, ":")
    for _, file := range files {
        fmt.Println(file)
    }
}

Explanation

Step 2: Implement a Function to List Files in the Directory

  • The listFiles function uses os.ReadDir to read the contents of the specified directory:
    • os.ReadDir returns a slice of os.DirEntry objects, which represent the files and directories in the specified directory.
    • The function iterates over the returned entries, appending the names of the files and directories to a slice of strings.
    • The function returns the slice of filenames and directories, or an error if the directory could not be read.

Step 3: Write the Main Function

  • The main function prompts the user for the directory path and calls listFiles to list the files and directories.

Step 4: Prompt the User to Enter the Directory Path

  • The program prompts the user to enter the directory path using fmt.Print and reads the input using fmt.Scanln.

Step 5: Call the Function to List Files in the Directory

  • The program calls listFiles with the provided directory path to list the files and directories.

Step 6: Display the Result

  • The program prints the names of the files and directories using fmt.Println.

Output Example

Example 1:

Enter the directory path: ./mydir
Files and directories in ./mydir :
file1.txt
file2.txt
subdir1
subdir2

Example 2:

Enter the directory path: ./nonexistentdir
Error reading directory: open ./nonexistentdir: no such file or directory

Example 3 (Empty directory):

Enter the directory path: ./emptydir
Files and directories in ./emptydir :

Conclusion

This Go program demonstrates how to list files and directories in a specified directory using the os package. It covers basic file operations such as reading directory contents and handling errors in Go. This example is useful for beginners learning Go programming and understanding how to interact with the file system effectively.

Leave a Comment

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

Scroll to Top