Skip to content

Instantly share code, notes, and snippets.

@toddlers
Created January 25, 2017 13:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toddlers/2cf1b77f0d64b8bf959f1073c2e85b84 to your computer and use it in GitHub Desktop.
Save toddlers/2cf1b77f0d64b8bf959f1073c2e85b84 to your computer and use it in GitHub Desktop.
getting fileinfo in go
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())
}
@jabbalaci
Copy link

Thanks, exactly what I needed.

@dablelv
Copy link

dablelv commented Nov 22, 2022

Why it can't work on the Winodws?

@fetidbell
Copy link

fetidbell commented Jan 4, 2023

Hey guys, maybe someone can explain me what is going on on line 28? I'll really appreciate for it. I can't understand this one specifically:
fileInfo.Mode()&os.ModeSymlink
what is & doing here? It looks like a pointer thing, but why it goes directly after function call? Please, correct me if I'm wrong.
Thanks in advance!

@jabbalaci
Copy link

That & is a bitwise AND operation. You check if the os.ModeSymlink bit is set.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment