Open In App

How to Check File Size and Last Modified Time in Golang?

Improve
Improve
Like Article
Like
Save
Share
Report

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




// Golang program to check the size and 
// modified time of a file
package main
  
// Importing the required packages
import (
    "fmt"
    "log"
    "os"
)
  
func main() {
  
    // Get the fileinfo
    fileInfo, err := os.Stat("cpnew.txt")
  
    // Checks for the error
    if err != nil {
        log.Fatal(err)
    }
  
    // Gives the modification time
    modificationTime := fileInfo.ModTime()
    fmt.Println("Name of the file:", fileInfo.Name(), 
                " Last modified time of the file:"
                modificationTime)
  
    // Gives the size of the file in bytes
    fileSize := fileInfo.Size()
    fmt.Println("Size of the file:", fileSize)
}


Output:

Size of file

 

Example 2: Below is the Golang program to check the existence of the file.

Fig 1


Go




// Golang program to check the existence of a file
package main
  
// Importing required packages
import (
    "errors"
    "fmt"
    "os"
)
  
func main() {
  
    _, err := os.Stat("cpnew.txt")
  
    // Is reports whether any error in err's tree 
    // matches the target.
    // Here our target error is os.ErrNotExist
    // When the err equals to ErrNotExist it returns 
    // true which means the file doesn't exist in the directory
    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:

File exists

 



Last Updated : 08 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads