I'm trying to get the posix permissions of a file, but when I use the key FileAttributeKey.posixPermissions
(originally NSFilePosixPermissions
) to retrieve the numerical posix permissions value, it returned 511 (-r-x--x--x)
, but when I use stat -f %A /path/to/file
in Terminal, it returned 777 (-rwxrwxrwx)
which is the correct one (I used chmod 777 /path/to/file
, so it should be 777 (-rwxrwxrwx)
).
This is my code using FileAttributeKey.posixPermissions
(Swift 4):
var numericalValue = "000"
if let attributes = try? FileManager.default.attributesOfItem(atPath: "/path/to/file") {
if let posixPermissions = attributes[.posixPermissions] as? NSNumber {
numericalValue = posixPermissions.stringValue
}
}
I don't know what is going on, I'm wondering how is the value returned from FileAttributeKey.posixPermissions
different from the output of stat -f %A /path/to/file
or stat -x /path/to/file
, can anyone please help me to figure out?
You need to display the result in octal:
if let attributes = try? FileManager.default.attributesOfItem(atPath: "/path/to/file") {
if let posixPermissions = attributes[.posixPermissions] as? NSNumber {
let octal = String(posixPermissions.intValue, radix: 8, uppercase: false)
print(octal)
}
}