代码之家  ›  专栏  ›  技术社区  ›  Vassilis

目标C人类可读nsstring的nsvillepositionexpermissions

  •  6
  • Vassilis  · 技术社区  · 14 年前

    有没有一种方法可以从nsFilePosiExpermissions整数中获取可读字符串(@“drwxr-xr-x”例如)?

    2 回复  |  直到 14 年前
        1
  •  5
  •   dreamlax    14 年前

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

    // 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
  •  0
  •   ennuikiller    14 年前

    我想你可以创建一个这样的数组:

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

    然后,将nsfilepositionexpermissions转换为八进制后,将生成的数字拆分为其component数字,并使用converttoalpha将每个数字映射到其字母数字表示…

    推荐文章