2010-11-08 64 views
6

是否有一種方法來從NSFilePosixPermissions整數獲取人類可讀的字符串(例如@「drwxr-xr-x」)?objective-c NSFilePosixPermissions到人類可讀的NSString

+0

不是。如果沒有獨角獸護符和一大堆酒,完全不可能。 (請參閱按位操作:http://en.wikipedia.org/wiki/Bitwise_operation) – 2010-11-08 19:20:34

+0

(上傳問題,因爲它是一個很好的問題,我是一個聰明的**):-) – 2010-11-08 19:24:35

+0

謝謝約書亞!接受的答案似乎很好! – Vassilis 2010-11-09 01:05:53

回答

4

文件系統權限屬性只是一個無符號長整型值。下面的代碼顯然可以提高效率,但它顯示[或多或少]需要做些什麼來獲得所需的字符串:

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

嗯,我想你可以創建一個數組,像這樣:

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

然後tranlating的NSFilePosixPermissions爲八進制數之後,拆分導致數到它的組元的數字,並使用convertToAlpha映射每一位數字的字母數字表示。 ...

+0

xm ...我會嘗試。我會回來,如果我做到了,發佈整個解決方案。謝謝! – Vassilis 2010-11-08 19:52:15

+0

@VassilisGr @ennuikiller:儘管如此,你需要在每個字符串後面有一個@符號,並且還需要在你的參數列表中添加'nil'。 – dreamlax 2010-11-08 20:16:16

+0

@dreamlax,感謝您的更正! – ennuikiller 2010-11-08 20:53:36