对人类可读的NSString的Objective-C NSFilePosixPermissions [英] objective-c NSFilePosixPermissions to human readable NSString

查看:252
本文介绍了对人类可读的NSString的Objective-C NSFilePosixPermissions的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从NSFilePosixPermissions整数中获取人类可读的字符串(例如@"drwxr-xr-x")?

is there a way to get human readable string (@"drwxr-xr-x" for example) from an NSFilePosixPermissions integer ?

推荐答案

文件系统权限属性只是一个无符号的long值.显然,下面的代码可以提高效率,但是它(或多或少)显示了获取所需字符串需要做什么:

The file system permissions attribute is simply an unsigned long value. The code below could obviously be made more efficient but it shows [more or less] what needs to be done to get the string you want:

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

这篇关于对人类可读的NSString的Objective-C NSFilePosixPermissions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆