objective-c NSFilePosixPermissions 到人类可读的 NSString

标签 objective-c permissions nsstring posix human-readable

有没有办法从 NSFilePosixPermissions 整数中获取人类可读的字符串(例如@"drwxr-xr-x")?

最佳答案

文件系统权限属性只是一个无符号长值。下面的代码显然可以提高效率,但它 [或多或少] 显示了获取所需字符串需要做的事情:

// The indices of the items in the permsArray correspond to the POSIX
// permissions. Essentially each bit of the POSIX permissions represents
// a read, write, or execute bit.
NSArray *permsArray = [NSArray arrayWithObjects:@"---", @"--x", @"-w-", @"-wx", @"r--", @"r-x", @"rw-", @"rwx", nil];
NSFileManager *fm = [[[NSFileManager alloc] init] autorelease];
NSMutableString *result = [NSMutableString string];
NSDictionary *attrs = [fm attributesOfItemAtPath:@"some/path.txt" error:NULL];

if (!attrs)
    return nil;

NSUInteger perms = [attrs filePosixPermissions];

if ([[attrs fileType] isEqualToString:NSFileTypeDirectory])
    [result appendString:@"d"];
else
    [result appendString:@"-"];

// loop through POSIX permissions, starting at user, then group, then other.
for (int i = 2; i >= 0; i--)
{
    // this creates an index from 0 to 7
    unsigned long thisPart = (perms >> (i * 3)) & 0x7;

    // we look up this index in our permissions array and append it.
    [result appendString:[permsArray objectAtIndex:thisPart]];
}

return result;

关于objective-c NSFilePosixPermissions 到人类可读的 NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4127147/

相关文章:

c# - 使用 Azure AD Graph 客户端 API 更改用户密码的权限问题

ios - 如何将 JSON 字符串反序列化为 NSDictionary? (适用于 iOS 5+)

ios - 将字符串添加到 uibutton 标题

objective-c - 为什么我会收到构建警告,说 : "data argument not used by format string"?

iphone - Core Data 最大存储空间 iPhone

java - java中如何实现权限控制?

c# - WMI:远程编辑注册表

iphone - 应用程序文档目录的物理路径

objective-c - BSXPCMessage 收到消息 : Connection interrupted on CIContext with iOS 8 的错误

ios - 在 Swift 中匹配独立的子字符串