How to convert filemode to int?

Sample code:

func main() {
    p, _ := os.Open(os.Args[1])
    m, _ := p.Stat()
    println(m.Mode().Perm())
}

File has mode 0775 (-rwxrwxr-x). Running it like:

./main main

Prints 509

And second:

func main() {
    p, _ := os.Open(os.Args[1])
    m, _ := p.Stat()
    println(m.Mode().Perm().String())
}

This code prints -rwxrwxr-x.

How I can get mode in format 0775?

Upvotes: 4

Views: 2676

Answers (1)

icza
icza

Reputation: 417592

The value 509 is the decimal (base 10) representation of the permission bits.

The form 0775 is the octal representation (base 8). You can print a number in octal representation using the %o verb:

perm := 509
fmt.Printf("%o", perm)

Output (try it on the Go Playground):

775

If you want the output to be 4 digits (with a leading 0 in this case), use the format string "%04o":

fmt.Printf("%04o", perm) // Output: 0775

Upvotes: 7

Related Questions