is there a way to get human readable string (@"drwxr-xr-x" for example) from an NSFilePosixPermissions integer ?
Asked
Active
Viewed 3,316 times
6
-
Nope. Completely impossible without the Unicorn Talisman and a whole lot of liquor. (See Bitwise Operations: http://en.wikipedia.org/wiki/Bitwise_operation) – Joshua Nozzi Nov 08 '10 at 19:20
-
(Up-voted the question since it's a good one and I'm being a smart-a**.) :-) – Joshua Nozzi Nov 08 '10 at 19:24
-
Thanks Joshua! the accepted answer seems to be fine! – Vassilis Nov 09 '10 at 01:05
2 Answers
5
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;

dreamlax
- 93,976
- 29
- 161
- 209
0
Well I guess you can create an array like so:
NSArray *convertToAlpha = [NSArray arrayWithObjects:@"---",@"--x",@"-w-",@"--wx",@"r--",@"r-x",@"rw-",@"rwx", nil];
Then after tranlating the NSFilePosixPermissions to octal, split the resulting number into its componenet digits and use convertToAlpha to map each digit to its alphanumeric representation....

ennuikiller
- 46,381
- 14
- 112
- 137
-
xm... I'll try that. I'll get back if I make it, to post the entire solution. Thank you! – Vassilis Nov 08 '10 at 19:52
-
@VassilisGr, @ennuikiller: beware though, you need an `@` symbol behind each string, and also need to add `nil` to your list of arguments. – dreamlax Nov 08 '10 at 20:16