2010-11-08 22 views
6

Y at-il un moyen d'obtenir une chaîne lisible par un humain (@ "drwxr-xr-x" par exemple) à partir d'un entier NSFilePosixPermissions?Objectif-c NSFilePosixPermissions à lisible par l'homme NSString

+0

Non. Complètement impossible sans le Talisman Unicorn et beaucoup d'alcool. (Voir Opérations bitwise: http://en.wikipedia.org/wiki/Bitwise_operation) –

+0

(Up-voté la question car c'est un bon et je suis un smart-a **.) :-) –

+0

Merci Joshua ! la réponse acceptée semble être bien! – Vassilis

Répondre

4

L'attribut permissions du système de fichiers est simplement une valeur longue non signée. Le code ci-dessous pourrait évidemment être rendu plus efficace mais il montre [plus ou moins] ce qui doit être fait pour obtenir la chaîne que vous voulez:

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

Eh bien, je suppose que vous pouvez créer un tableau comme ceci:

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

Puis, après tranlating les NSFilePosixPermissions octal, diviser le nombre obtenu dans ses chiffres Componenet et utiliser convertToAlpha pour cartographier chaque chiffre à sa représentation alphanumérique. ...

+0

xm ... Je vais essayer ça. Je reviendrai si je le fais, pour poster toute la solution. Je vous remercie! – Vassilis

+0

@VassilisGr, @ennuikiller: attention, vous avez besoin d'un symbole '@' derrière chaque chaîne, et aussi besoin d'ajouter 'nil' à votre liste d'arguments. – dreamlax

+0

@dreamlax, merci pour les corrections! – ennuikiller