2012-01-02 30 views
2

我是新的objective-c。 我有一個包含在NSString中的文件的路徑,我想要獲取文件大小。我發現這example並更改不合法的代碼與attributesOfItemAtPath:錯誤:但路徑始終無效。獲取文件大小給出的路徑

NSFileManager *fileManager = [[NSFileManager alloc] init]; 
NSString *path = @"~/Library/Safari/History.plist"; 
NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath: path error: NULL]; 


if (fileAttributes != nil) { 
    NSNumber *fileSize; 

    if (fileSize == [fileAttributes objectForKey:NSFileSize]) { 
     NSLog(@"File size: %qi\n", [fileSize unsignedLongLongValue]); 
    } 

} 
else { 
    NSLog(@"Path (%@) is invalid.", pPath); 
} 
[NSFileManager release]; 

回答

4

這應該工作:

uint64_t fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:_filePath error:nil] fileSize]; 

它非常類似於你所使用的,但在你有一個錯誤:你把NULL,而不是nilerror:處理。

還需確保在您的路徑擴大波浪線,如documentation解釋:使用stringByExpandingTildeInPath,所以你NSString *path應該是這樣的:

NSString *path = [[NSString stringWithString:@"~/Library/Safari/History.plist"] stringByExpandingTildeInPath]; 

Here你可以找到關於nil之間的差別一些解釋和NULL

+0

我認爲這個問題不是波浪號(〜),用NSString * path = @「Whatever.txt」;該代碼不起作用。 – Joannes 2012-01-02 10:07:17

+0

你是否在錯誤處理中用'nil'而不是'NULL'嘗試過?我發佈的代碼已經過測試,並在我的一些應用程序中使用,所以我確信它可以正常工作。嘗試**完整路徑**,例如**/Users/USERNAME/Library/Safari/History.plist **並使用'NSFileManager'的'defaultMangaer'來代替創建自己的實例。 [這裏(http://pastebin.com/XBBCvqGu)](http://pastebin.com/XBBCvqGu)我寫了一段代碼,它可以做你正在尋找的東西:它已經過測試並且可以正常工作。 – Sylter 2012-01-02 11:04:15

+0

我試過零,並沒有錯誤,但代碼不起作用。在控制檯中,我嘗試了你的代碼,沒關係,但是我需要輸入你的用戶名。我怎麼能不放呢?只/圖書館/ Safari/History.plist? – Joannes 2012-01-02 12:21:27

1

您可能需要使用擴展的路徑:

- (NSString *)stringByExpandingTildeInPath 
+0

該方法的評分較低。我喜歡它:)比stringWithFormat和NSHomeDirectory()更簡單,更可讀。 – 2013-07-21 03:10:15

0

使用defaultManager類方法上的NSFileManager,而不是創建自己的實例。此外,不要在文件路徑中包含~(代字號)符號。使用NSHomeDirectory()函數來取代主目錄。這裏有一個例子:

NSString *path = [NSString stringWithFormat:@"%@/Library/Safari/History.plist", NSHomeDirectory()]; 
[[[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil] fileSize]; 

這應該會返回文件的大小。

+0

without NSDictionary * fileAttributes其餘的代碼不起作用。確定沒有〜使用例如NSString * path = @「Whatever.txt」; NSDictionary * fileAttributes = [fileManager attributesOfItemAtPath:path error:NULL];該代碼不能再工作。 – Joannes 2012-01-02 10:16:04

1

你可以得到大小:

NSDictionary * properties = [[NSFileManager defaultManager] attributesOfItemAtPath:yourFilePath error:nil]; 
NSNumber * size = [properties objectForKey: NSFileSize]; 

大小是包含無符號long長的NSNumber。

1

由於代碼中存在超級愚蠢的錯誤,您的路徑將始終無效。

變化

if (fileSize == [fileAttributes objectForKey:NSFileSize]) { 

if (fileSize = [fileAttributes objectForKey:NSFileSize]) { 

我希望沒有進一步explanatiuon將需要。