Go Program to Get File Metadata

Go Program to Get File Details

This Go code is used to read the file details like metadata name, last modified timestamp, permission mode etc..

Getting information about files and directories is straightforward using os module.

This Go code uses os.Stat() function to return os.FileInfo object which is used to read the file metadata attributes.

package main

import (
	"fmt"
	"os"
)

func main() {
	file, err := os.Stat("/etc/java/java.conf")
	if err == nil {
		fmt.Println("File name: ", file.Name())
		fmt.Println("Size: ", file.Size(), " bytes")
		fmt.Println("Direcory: ", file.IsDir())
		fmt.Printf("Permission 9-bits: %s\n", file.Mode())
		fmt.Printf("Permission 4-digits: %o\n", file.Mode())
		fmt.Printf("Permission 3-digits: %o\n", file.Mode())
		fmt.Println("File Last Modified: ", file.ModTime())
	} else {
		fmt.Println("Invalid file!")
	}
}

Output:

$ go build file-metadata.go
$ ./file-metadata
File name:  java.conf
Size:  738  bytes
Direcory:  false
Permission 9-bits: -rw-r--r--
Permission 4-digits: 644
Permission 3-digits: 644
File Last Modified:  2017-07-03 19:08:18 +0530 IST

IsDir is used to check whether file is directory or not.

Mode function is used to get the file permission and can be formatted using fmt.Printf function.