2

I was recently playing with file modes and permissions in Go and stumbled upon the output when getting it.

The following code:

for _, file := range files {
    fmt.Println(file.Mode()) 
}  

produces output:

drwx------
Lrwxr-xr-x
drwxr--r--
drwx------
drwx------
prw-r--r--
Srw-rw-rw-
Srw-rw-rw-
-rw-r--r--

My question is how do I get permissions in numbers like 0777, etc.

Is there a similar way like in python provided in this answer: How can I get a file's permission mask??

Community
  • 1
  • 1

1 Answers1

7

Once you have the file mode (with FileInfo.Mode()), use the FileMode.Perm() method. This returns a value of type os.FileMode which has uint32 as its underlying type.

The format you're seeking (e.g. 0777) is in base 8. You can use e.g. fmt.Printf() with the verb %o to print a number in octal format (base 8). Use a width 4 to make it 4 digits, and a flag 0 to make it padded with 0's. So the format string for printing file permissions: "%04o".

So print it like this:

files, err := ioutil.ReadDir(".")
// Handle err

for _, file := range files {
    fmt.Printf("%s %04o %s\n", file.Mode(), file.Mode().Perm(), file.Name())
}

Example output:

-rw-rw-r-- 0664 play.go
drwxrwxr-x 0775 subplay
icza
  • 389,944
  • 63
  • 907
  • 827