Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objective-c NSFilePosixPermissions to human readable NSString

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

like image 375
Vassilis Avatar asked Nov 08 '10 19:11

Vassilis


1 Answers

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;
like image 51
dreamlax Avatar answered Sep 20 '22 09:09

dreamlax