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
- Name() string: It is the base name of the file,
- Size() int64: It is the length in bytes for regular files; system-dependent for others,
- Mode() FileMode: It is the file mode bits.
- ModTime() time.Time: It is the modification time.
- IsDir() bool: It is an abbreviation for Mode().IsDir()
- 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)
}
}
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

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.