Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 564
Андрей Антонов Avatar asked Sep 06 '25 04:09

Андрей Антонов


1 Answers

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
like image 178
icza Avatar answered Sep 07 '25 20:09

icza