Go: how to get infomation about files in a directory

Go: how to get infomation about files in a directory

In this article, we'll look at how to use the os package to read the contents of a directory and get information about files.

Go, also known as Golang, offers several built-in features to manage files and directories, making it easier for developers to work with the filesystem. In this article, we'll look at how to use the os package to read the contents of a directory and get information about files.

To read files from a directory in Go, we can use the ReadDir function from the os package. This function returns a slice of os.DirEntry, representing the directory entries.

Here is an example of how to use ReadDir:


package main

import (
     "fmt"
     "os"
)

func main() {
     // Path to the directory to read
     dirPath := "./"

     // Read the contents of the directory
     entries, err := os.ReadDir(dirPath)
     if err != nil {
         fmt.Println("Error reading directory:", err)
         os.Exit(1)
     }

     // Print the name of each entry found
     for _, entry := range entries {
         fmt.Println(entry.Name())
     }
}

To get detailed information about a specific file, such as size, permissions or modification times, we can use the Info() method found on an os.DirEntry< object /code> obtained from the ReadDir.

Here's how you can do it:


package main

import (
     "fmt"
     "os"
)

func main() {
     dirPath := "./"

     entries, err := os.ReadDir(dirPath)
     if err != nil {
         fmt.Println("Error reading directory:", err)
         os.Exit(1)
     }

     for _, entry := range entries {
         info, err := entry.Info()
         if err != nil {
             fmt.Println("Error getting file information:", err)
             continue
         }

         // Print file details
         fmt.Printf("Name: %s, Size: %d, Permissions: %s\n", info.Name(), info.Size(), info.Mode())
     }
}

These are just some basic examples of how to work with files and directories in Go. The os package provides many other useful functions that can help you perform more complex operations, such as changing permissions of files, checking whether an entry is a file or a directory, and much more.

Go makes working with the filesystem easy thanks to its well-designed standard library. Experimenting with these functions and reading the official documentation can help you take full advantage of the language's capabilities for file and directory operations.