【问题标题】:objective-c NSFilePosixPermissions to human readable NSStringObjective-c NSFilePosixPermissions 到人类可读的 NSString
【发布时间】:2010-11-08 19:15:54
【问题描述】:

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

【问题讨论】:

  • 不。没有独角兽护身符和一大堆酒,完全不可能。 (参见位运算:en.wikipedia.org/wiki/Bitwise_operation
  • (对这个问题投了赞成票,因为这是一个好问题,而且我是个聪明人。):-)
  • 谢谢约书亚!接受的答案似乎很好!

标签: objective-c permissions nsstring posix human-readable


【解决方案1】:

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

// 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;

【讨论】:

    【解决方案2】:

    我猜你可以像这样创建一个数组:

    NSArray *convertToAlpha = [NSArray arrayWithObjects:@"---",@"--x",@"-w-",@"--wx",@"r--",@"r-x",@"rw-",@"rwx", nil];
    

    然后将 NSFilePosixPermissions 转换为八进制后,将生成的数字拆分为其组件数字,并使用 convertToAlpha 将每个数字映射到其字母数字表示......

    【讨论】:

    • xm... 我会试试的。如果我成功了,我会回来发布整个解决方案。谢谢!
    • @VassilisGr, @ennukiller:但请注意,您需要在每个字符串后面添加一个 @ 符号,并且还需要将 nil 添加到您的参数列表中。
    猜你喜欢
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 2011-12-30
    • 2011-10-17
    相关资源
    最近更新 更多