Objective-C NSFilePosixPermissions 转换为易读的人类可读 NSString。

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

不行,没有独角兽护身符和大量的酒精是完全不可能的。(请参阅位运算:http://en.wikipedia.org/wiki/Bitwise_operation) - Joshua Nozzi
(我赞成这个问题,因为它很好,而且我表现得有点聪明。):-) - Joshua Nozzi
谢谢Joshua!被接受的答案看起来很好! - Vassilis
2个回答

5
文件系统权限属性仅是一个无符号长整型值。下面的代码显然可以更加高效,但它展示了[或多或少]需要完成的操作以获取所需字符串:
// 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;

0

好吧,我猜你可以这样创建一个数组:

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

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


xm... 我会尝试的。如果成功了,我会回来发布整个解决方案。谢谢! - Vassilis
@VassilisGr,@ennuikiller:请注意,你需要在每个字符串后面加上@符号,并且还需要将nil添加到您的参数列表中。 - dreamlax

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接