Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Get File Name, Size, Permission Bits, Mode, Modified Time in Go (Golang)

Posted on April 16, 2020April 16, 2020 by admin

Table of Contents

  • Overview
  • Code

Overview

os.Stat() function can be used to the info of a file in go. This function returns stats which can be used to get

  • Name of the file
  • Size of the file in bytes
  • Modified Time of the file
  • Permission Bits or Mode of the file

Below is the signature of the function. It takes in the named file and return FileInfo struct which defines utility method to get above information

func Stat(name string) (FileInfo, error)

Code

package main

import (
    "fmt"
    "log"
    "os"
)

func main() {
    //Create a file
    file, err := os.Create("temp.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    //Write something to the file
    file.WriteString("some sample text" + "\n")

    //Gets stats of the file
    stats, err := os.Stat("temp.txt")
    if err != nil {
        log.Fatal(err)
    }

    //Prints stats of the file
    fmt.Printf("Permission: %s\n", stats.Mode())
    fmt.Printf("Name: %s\n", stats.Name())
    fmt.Printf("Size: %d\n", stats.Size())
    fmt.Printf("Modification Time: %s\n", stats.ModTime())
}

Output:

Permission: -rwxrwxrwx
Name: temp.txt
Size: 17
Modification Time: 2020-04-16 22:26:47.080128602 +0530 IST
  • go
  • golang
  • mode
  • modified time
  • permission bits
  • size
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme