Golang os.Lstat(), Stat() functions and FileMode type example

package os

Golang os.Lstat(), Stat() functions and FileMode type usage example

 package main

 import (
 "fmt"
 "os"
 )

 func main() {

 // can handle symbolic link, but will no follow the link
 fileInfo, err := os.Lstat("file.txt")

 // cannot handle symbolic link
 //fileInfo, err := os.Lstat("file.txt")

 if err != nil {
 panic(err)
 }

 fmt.Println("Name : ", fileInfo.Name())

 fmt.Println("Size : ", fileInfo.Size())

 fmt.Println("Mode/permission : ", fileInfo.Mode())

 // --- check if file is a symlink

 if fileInfo.Mode()&os.ModeSymlink == os.ModeSymlink {
 fmt.Println("File is a symbolic link")
 }

 fmt.Println("Modification Time : ", fileInfo.ModTime())

 fmt.Println("Is a directory? : ", fileInfo.IsDir())

 fmt.Println("Is a regular file? : ", fileInfo.Mode().IsRegular())

 fmt.Println("Unix permission bits? : ", fileInfo.Mode().Perm())

 fmt.Println("Permission in string : ", fileInfo.Mode().String())

 fmt.Println("What else underneath? : ", fileInfo.Sys())

 }

Sample output :

Name : file.txt

Size : 95

Mode/permission : -rw-r--r--

Modification Time : 2015-06-19 12:00:55 +0800 SGT

Is a directory? : false

Is a regular file? : true

Unix permission bits? : -rw-r--r--

Permission in string : -rw-r--r--

What else underneath? : &{16777218 33188 1 6421054 501 20 0 [0 0 0 0] {1434686458 0} {1434686455 0} {1434686455 0} {1434685089 0} 95 8 4096 0 0 0 [0 0]}

References :

http://golang.org/pkg/os/#FileMode

http://golang.org/pkg/os/#Lstat

http://golang.org/pkg/os/#Stat

Advertisement