How to get information about a file or directory, such as size and modification time, using the os package in Golang?

To get information about a file or directory, such as size and modification time, using the os package in Golang, you can use the following steps:

  1. First, import the os package into your code:
import "os"
  1. Use the os.Stat() function to retrieve the file or directory information. The Stat() function returns a FileInfo object that contains various details about the file or directory. Here is an example to get information about a file:
fileInfo, err := os.Stat("path/to/file.txt") if err != nil { // handle error }
  1. Retrieve the required information from the FileInfo object. Here are some commonly used methods:
  • To get the file or directory name:

    name := fileInfo.Name()
  • To get the size of the file or directory in bytes:

    size := fileInfo.Size()
  • To get the last modification time of the file or directory:

    modTime := fileInfo.ModTime()

Note: If you need more specific details or additional information, you can explore other methods available in the FileInfo object. For example, you can use fileInfo.Mode() to get the file permissions.

That's it! You can now use the os package in Golang to retrieve information about files and directories using the Stat() function and the FileInfo object.