permission bits Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/permission-bits/ Thu, 16 Apr 2020 17:02:13 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://i0.wp.com/golangbyexamples.com/wp-content/uploads/2021/05/cropped-go_border-1.png?fit=32%2C32&ssl=1 permission bits Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/permission-bits/ 32 32 159787465 Get File Name, Size, Permission Bits, Mode, Modified Time in Go (Golang) https://vikasboss.github.io/file-info-golang/ https://vikasboss.github.io/file-info-golang/#respond Thu, 16 Apr 2020 17:02:01 +0000 https://vikasboss.github.io/?p=2014 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...

The post Get File Name, Size, Permission Bits, Mode, Modified Time in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
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

The post Get File Name, Size, Permission Bits, Mode, Modified Time in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/file-info-golang/feed/ 0 2014