Golang os.Stat Usage and Examples


GO

Author: Tuan Nguyen
Reviewer: Deepak Prasad

Introduction to golang os package

Working with files sometimes requires file metadata information. In today's article, we will strive for a way to get file info in Golang with detailed examples. Golang built-in package os provides types and functions to help us to work with files and directories:

os package: Package os provides a platform-independent interface to operating system functionality. The design is Unix-like, although the error handling is Go-like; failing calls return values of type error rather than error numbers. Often, more information is available within the error. For example, if a call that takes a file name fails, such as Open or Stat, the error will include the failing file name when printed and will be of type *PathError, which may be unpacked for more information.

 

Example-1: Get file information with os.Stat function

Without opening the file

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

type FileInfo:

// A FileInfo describes a file and is returned by Stat.
type FileInfo interface {
	Name() string       // base name of the file
	Size() int64        // length in bytes for regular files; system-dependent for others
	Mode() FileMode     // file mode bits
	ModTime() time.Time // modification time
	IsDir() bool        // abbreviation for Mode().IsDir()
	Sys() any           // underlying data source (can return nil)
}

Here is an example of getting the file info without opening it. After we have type FileInfo, we can print this struct out to the console:

package main

import (
	"fmt"
	"os"
)

func main() {
	//file name
	path := "./data.txt"

	//get file info
	fileInfo, err := os.Stat(path)
	//handle error
	if err != nil {
		panic(err)
	}

	// print file info
	fmt.Printf("File info: %+v\n", fileInfo)
}

Output:

File info: &{name:data.txt size:52 mode:436 modTime:{wall:145648606 ext:63802720083 loc:0x53e9a0} sys:{Dev:66307 Ino:42344757 Nlink:1 Mode:33204 Uid:1000 Gid:1000 X__pad0:0 Rdev:0 Size:52 Blksize:4096 Blocks:8 Atim:{Sec:1667123283 Nsec:149648694} Mtim:{Sec:1667123283 Nsec:145648606} Ctim:{Sec:1667123283 Nsec:145648606} X__unused:[0 0 0]}}

 

Open the file to get file information

In the example below, we will open the file and then get the file information by Stat() function:

package main

import (
	"fmt"
	"os"
)

func main() {
	// file name
	path := "./data.txt"

	// open file
	file, err := os.Open(path)
	if err != nil {
		panic(err)
	}

	// get file info
	fileInfo, err := file.Stat()
	if err != nil {
		panic(err)
	}

	// print file info
	fmt.Printf("File info: %+v\n", fileInfo)
}

Output:

File info: &{name:test.txt size:52 mode:420 modTime:{wall:271008975 ext:63801858651 loc:0x53c820} sys:{Dev:64769 Ino:396430 Nlink:1 Mode:33188 Uid:0 Gid:0 X__pad0:0 Rdev:0 Size:52 Blksize:4096 Blocks:8 Atim:{Sec:1666261851 Nsec:271008975} Mtim:{Sec:1666261851 Nsec:271008975} Ctim:{Sec:1666261851 Nsec:271008975} X__unused:[0 0 0]}}

 

Example-2: Check if file exists with os.Stat function

In this example, we will see how to check file existence in Golang with os.Stat and IsNotExist() function:

func IsNotExist(err error) bool: IsNotExist returns a boolean indicating whether the error is known to report that a file or directory does not exist. It is satisfied by ErrNotExist as well as some syscall errors.

Directory structure:

├── data_test
│   └── data_test.txt
├── data.txt
└── osStat.go
package main

import (
	"fmt"
	"os"
)

func main() {
	// file name
	path1 := "./data.txt"
	path2 := "./data2.txt"
	path3 := "./data_test"

	fmt.Println("File", path1, "exist?:", checkFileExists(path1))
	fmt.Println("File", path2, "exist?:", checkFileExists(path2))
	fmt.Println("File", path3, "exist?:", checkFileExists(path3))

}

// check file exists
func checkFileExists(fname string) bool {
	info, err := os.Stat(fname)
	if os.IsNotExist(err) {
		return false
	}
	return !info.IsDir()
}

Output:

File ./data.txt exist?: true
File ./data2.txt exist?: false
File ./data_test exist?: false

 

Summary

The code shown above illustrates how to use os.Stat() function to get file info or check if a file exists in Golang. Please share any more approaches you are aware of that are not listed above in the comments.

 

References

https://pkg.go.dev/os

 

Views: 370
Tuan Nguyen

Tuan Nguyen

He is proficient in Golang, Python, Java, MongoDB, Selenium, Spring Boot, Kubernetes, Scrapy, API development, Docker, Data Scraping, PrimeFaces, Linux, Data Structures, and Data Mining. With expertise spanning these technologies, he develops robust solutions and implements efficient data processing and management strategies across various projects and platforms. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment