Objective-C NSFilePosixpermissmiss of Human可读性NSString
-
29-09-2019 - |
题
有没有办法从nsfileposixpermissions Integer中获取人类可读字符串(例如@“ 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;
其他提示
好吧,我想您可以创建一个类似的数组:
NSArray *convertToAlpha = [NSArray arrayWithObjects:@"---",@"--x",@"-w-",@"--wx",@"r--",@"r-x",@"rw-",@"rwx", nil];
然后,将NSFilePosixpermissions旋转到八进制后,将结果编号拆分为其组合数字,并使用converttoalpha将每个数字映射到其字母数字表示。
不隶属于 StackOverflow