NSFilePosixPermissions objectif-c à NSString lisible par l'homme
-
29-09-2019 - |
Question
est-il un moyen d'obtenir la chaîne lisible par l'homme (@ "drwxr-xr-x", par exemple) à partir d'un nombre entier de NSFilePosixPermissions?
La solution
Les permissions du système d'attributs de fichier est tout simplement une valeur unsigned long. Le code ci-dessous pourrait évidemment être 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;
Autres conseils
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];
Alors après tranlating les NSFilePosixPermissions à octal, divisé le nombre obtenu dans ses chiffres Componenet et utiliser convertToAlpha pour cartographier chaque chiffre à sa représentation alphanumérique ....
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow