How to Check File Size and Last Modified Time in Golang?
Last Updated :
08 Apr, 2023
In the Go language, the os module provides the ability to access native operating-system features. In the os package, the Stat() function is used to check the file size and last modified time. This method gives the FileInfo structure describing the file and an error of type *PathError.
// FileInfo describes a file and is returned by the stat
type FileInfo interface{
Name() string
Size() int64
Mode() FileMode
ModTime() time.Time()
IsDir() bool
Sys() any
}
The following methods of FileInfo are used to get the name, size, and last modified time of the file:
Name(): Returns the name of the file.
Size(): Gives the length in bytes for regular files and system dependent for other files.
ModTime(): Gives the last modified time of the file.
Example 1: Below is the Golang program to check the size and modified time of the file.
Go
package main
import (
"fmt"
"log"
"os"
)
func main() {
fileInfo, err := os.Stat( "cpnew.txt" )
if err != nil {
log.Fatal(err)
}
modificationTime := fileInfo.ModTime()
fmt.Println( "Name of the file:" , fileInfo.Name(),
" Last modified time of the file:" ,
modificationTime)
fileSize := fileInfo.Size()
fmt.Println( "Size of the file:" , fileSize)
}
|
Output:
Example 2: Below is the Golang program to check the existence of the file.
Fig 1
Go
package main
import (
"errors"
"fmt"
"os"
)
func main() {
_, err := os.Stat( "cpnew.txt" )
if errors.Is(err, os.ErrNotExist) {
fmt.Println( "File does not exist" )
} else
{
fmt.Println( "File exists" )
}
_, err1 := os.Stat( "test.txt" )
if errors.Is(err1, os.ErrNotExist) {
fmt.Println( "File does not exist" )
} else
{
fmt.Println( "File exists" )
}
}
|
Output:
Share your thoughts in the comments
Please Login to comment...