Golang os.Stat() Function

Golang os.Stat() function returns the “FileInfo structure describing the file, which contains information such as its size, modification time, and mode.” If there is an error, it will be of type *PathError.

Syntax

func Stat(name string) (FileInfo, error)

Parameters

name: It is a file path as an argument.

Return value

The Stat() function returns a FileInfo describing the named file. If there is an error, it will be of type *PathError.

The FileInfo object contains

  1. Name() string: It is the base name of the file,
  2. Size() int64: It is the length in bytes for regular files; system-dependent for others,
  3. Mode() FileMode: It is the file mode bits.
  4. ModTime() time.Time: It is the modification time.
  5. IsDir() bool: It is an abbreviation for Mode().IsDir()
  6. Sys() any

Example 1: How to Use os.Stat() function

package main

import (
  "fmt"
  "os"
)

func main() {
  path_to_file := "../file.txt"
  fileInfo, err := os.Stat(path_to_file)
  if err != nil {
    panic(err)
  }
  
  // Use the FileInfo type to access the file's properties
  fmt.Println("File Name:", fileInfo.Name())
  fmt.Println("File size:", fileInfo.Size())
  fmt.Println("Last modified:", fileInfo.ModTime())
  fmt.Println("Permissions:", fileInfo.Mode())
}

Output

File Name: file.txt
File size: 12
Last modified: 1979-11-30 00:00:00 +0530 IST
Permissions: -rw-rw-r--

Example 2: Checking If a File Exists

package main

import (
  "fmt"
  "os"
)

func main() {
  fileName := "new.txt"

  _, err := os.Stat(fileName)
  if os.IsNotExist(err) {
    fmt.Printf("File %s does not exist.\n", fileName)
  } else {
    fmt.Printf("File %s exists.\n", fileName)
  }
}

Output

File new.txt exists.

Example 3: Determining if the Path is a Directory or a File

package main

import (
  "fmt"
  "os"
)

func main() {
  path := "new.txt"

  fileInfo, err := os.Stat(path)
  if err != nil {
    fmt.Println("Error:", err)
    return
  }

  if fileInfo.IsDir() {
    fmt.Printf("%s is a directory.\n", path)
  } else {
    fmt.Printf("%s is a file.\n", path)
  }
}
Output
new.txt is a file.

Important Note!

Go os.Stat() function only works on regular files and directories. If you attempt to call os.Stat() on a symbolic link will return the FileInfo type for the target of the symbolic link, not the symbolic link itself.

To check if a symbolic link exists, use the os.Lstat() function.

That’s it.

Related posts

Golang os.Chown()

Golang os.Chmod()

Golang os.Chdir()

Golang os.Exit()

Leave a Comment