0
0
GoHow-ToBeginner · 3 min read

How to Get File Info in Go: Syntax and Example

In Go, you can get file information using the os.Stat function which returns a FileInfo object. This object provides details like file size, permissions, and modification time.
📐

Syntax

The main function to get file info is os.Stat(name string) (os.FileInfo, error). It takes the file path as input and returns a FileInfo object and an error if the file does not exist or cannot be accessed.

The FileInfo interface provides methods like Name(), Size(), Mode(), ModTime(), and IsDir() to get file details.

go
info, err := os.Stat("filename.txt")
if err != nil {
    // handle error
}
name := info.Name()
size := info.Size()
mode := info.Mode()
modTime := info.ModTime()
isDir := info.IsDir()
💻

Example

This example shows how to get and print file information such as name, size, permissions, and modification time for a file named example.txt.

go
package main

import (
    "fmt"
    "os"
)

func main() {
    info, err := os.Stat("example.txt")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println("File Name:", info.Name())
    fmt.Println("Size (bytes):", info.Size())
    fmt.Println("Permissions:", info.Mode())
    fmt.Println("Last Modified:", info.ModTime())
    fmt.Println("Is Directory?:", info.IsDir())
}
Output
File Name: example.txt Size (bytes): 1234 Permissions: -rw-r--r-- Last Modified: 2024-06-01 15:04:05 +0000 UTC Is Directory?: false
⚠️

Common Pitfalls

  • Not checking the error returned by os.Stat can cause your program to panic if the file does not exist.
  • Confusing os.Stat with os.Lstat: os.Lstat does not follow symbolic links, while os.Stat does.
  • Assuming the file is always a regular file; always check IsDir() to handle directories properly.
go
package main

import (
    "fmt"
    "os"
)

func main() {
    // Wrong: ignoring error
    info, _ := os.Stat("nofile.txt")
    if info != nil {
        fmt.Println("File Name:", info.Name()) // This will panic if file doesn't exist
    }

    // Right: check error
    info, err := os.Stat("nofile.txt")
    if err != nil {
        fmt.Println("File not found or error:", err)
        return
    }
    fmt.Println("File Name:", info.Name())
}
Output
File not found or error: stat nofile.txt: no such file or directory
📊

Quick Reference

Use os.Stat to get file info. Check the error before using the info. Use FileInfo methods to get details:

  • Name(): file name
  • Size(): file size in bytes
  • Mode(): file permissions
  • ModTime(): last modification time
  • IsDir(): true if directory

Key Takeaways

Use os.Stat to get file information and always check for errors.
FileInfo methods provide file name, size, permissions, modification time, and directory status.
Handle errors properly to avoid panics when the file does not exist.
Use IsDir() to distinguish files from directories.
os.Stat follows symbolic links; use os.Lstat if you want to avoid that.