6

NSFilePosixPermissions整数から人間が読める文字列(@ "drwxr-xr-x"など)を取得する方法はありますか?

4

2 に答える 2

5

ファイルシステムのパーミッション属性は、単にunsignedlong値です。以下のコードは明らかにより効率的にすることができますが、必要な文字列を取得するために何をする必要があるかを[多かれ少なかれ]示しています。

// 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;
于 2010-11-08T20:46:03.110 に答える
0

そうですね、次のような配列を作成できると思います。

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

次に、NSFilePosixPermissionsを8進数に変換した後、結果の数値をそのコンポーネントの数字に分割し、convertToAlphaを使用して各数字を英数字表現にマップします。

于 2010-11-08T19:35:01.613 に答える