Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Cocoa 如何';使用FileAttributeKey.posixPermissions与使用stat-f%A不同?_Cocoa_Swift4_Nsfilemanager_Stat - Fatal编程技术网

Cocoa 如何';使用FileAttributeKey.posixPermissions与使用stat-f%A不同?

Cocoa 如何';使用FileAttributeKey.posixPermissions与使用stat-f%A不同?,cocoa,swift4,nsfilemanager,stat,Cocoa,Swift4,Nsfilemanager,Stat,我试图获取文件的posix权限,但当我使用键FileAttributeKey.posixPermissions(最初是NSFilePosixPermissions)检索数字posix权限值时,它返回511(-r-x--x--x),但当我在终端中使用stat-f%a/path/to/file时,它返回了正确的777(-rwxrwx)(我使用了chmod 777/path/to/file,因此它应该是777(-rwxrwx)) 这是我使用FileAttributeKey.posixPermissio

我试图获取文件的posix权限,但当我使用键
FileAttributeKey.posixPermissions
(最初是
NSFilePosixPermissions
)检索数字posix权限值时,它返回
511(-r-x--x--x)
,但当我在终端中使用
stat-f%a/path/to/file
时,它返回了正确的
777(-rwxrwx)
(我使用了
chmod 777/path/to/file
,因此它应该是
777(-rwxrwx)

这是我使用
FileAttributeKey.posixPermissions
(Swift 4)编写的代码:


我不知道发生了什么,我想知道从
FileAttributeKey.posixPermissions
返回的值与
stat-f%A/path/to/file
stat-x/path/to/file
的输出有何不同,有谁能帮我弄清楚吗?

您需要以八进制显示结果:

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)
    }
}

这是一个有趣的问题!幸运的是,Swift有一个真正有用的字符串初始化函数。是的,它工作了,但我仍然不明白,这个初始化函数做什么?NSNumber只是一个数值,没有关于如何显示它的隐式指令。但是你可以用多种方式向人类展示一个数字。例如,你可以用罗马数字来显示它。但通常的方法是小数点显示,即使用0到9。这就是所谓的“基数10”。此init函数可用于此目的,基数参数设置为10。但这很愚蠢,您只需使用(字符串描述:)。但对于八进制表示法(使用数字0-7),您可以将基数设置为8。对于十六进制(使用数字0-9和A-F),将基数设置为16。
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)
    }
}