2009-05-02 105 views

回答

73

請記住fileAttributesAtPath:traverseLink:自Mac OS X v10.5起不推薦使用。改爲使用attributesOfItemAtPath:error:,在same URL處說明。

需要提醒的是我是一個Objective-C的新手,而我忽略了可能發生的調用attributesOfItemAtPath:error:錯誤,您可以執行以下操作:

NSString *yourPath = @"Whatever.txt"; 
NSFileManager *man = [NSFileManager defaultManager]; 
NSDictionary *attrs = [man attributesOfItemAtPath: yourPath error: NULL]; 
UInt32 result = [attrs fileSize]; 
+2

此代碼泄漏了分配的FileManager。我建議你簡單地使用NSFileManager.defaultManager單例來避免這種情況。 – 2012-10-18 10:07:47

122

這一個襯墊可以幫助人們:

unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:someFilePath error:nil] fileSize]; 

這將返回字節中的文件大小。

+2

我喜歡這個。但是這是什麼測量?字節,Kb等?也謝謝你。 – James 2012-01-03 13:55:39

+6

字節 - 測量字節爲 – 2012-01-11 09:18:28

+0

好的,謝謝。非常感激。 – James 2012-01-11 13:24:14

10

CPU raises with attributesOfItemAtPath:error:
您應該使用stat

#import <sys/stat.h> 

struct stat stat1; 
if(stat([inFilePath fileSystemRepresentation], &stat1)) { 
     // something is wrong 
} 
long long size = stat1.st_size; 
printf("Size: %lld\n", stat1.st_size); 
+0

以上不應該在這裏使用fileSystemRepresentation而不是UTF8String? – 2013-01-23 11:41:12

+0

你說得對。 HFS +爲文件名定義了標準的Unicode分解(「規範分解」)。 -UTF8String不保證返回正確的組合; -fileSystemRepresentation is。[1](http://cocoadev.com/wiki/StringWithCString) – 2013-01-28 07:11:32

+0

@ParagBafna我知道這是一個古老的線程,但你知道我怎樣才能在swift中使用'stat'結構嗎? – 2015-06-26 22:05:38

6

在從俄德本多夫的答案,我寧願在這裏使用的對象:

NSNumber * mySize = [NSNumber numberWithUnsignedLongLong:[[[NSFileManager defaultManager] attributesOfItemAtPath:someFilePath error:nil] fileSize]]; 
17

萬一有人需要斯威夫特版本:

let attr: NSDictionary = try! NSFileManager.defaultManager().attributesOfItemAtPath(path) 
print(attr.fileSize()) 
2

雨燕2.2:

do { 
    let attr: NSDictionary = try NSFileManager.defaultManager().attributesOfItemAtPath(path) 
    print(attr.fileSize()) 
} catch { 
     print(error) 
} 
1

它會給文件大小以字節。 ..

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

如果只想文件大小與字節只使用,文件大小(從字節)的精確KB,MB,GB

unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:yourAssetPath error:nil] fileSize]; 

NSByteCountFormatter字符串轉換...它的回報像120 MB120 KB

NSError *error = nil; 
NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:yourAssetPath error:&error]; 
if (attrs) { 
    NSString *string = [NSByteCountFormatter stringFromByteCount:fileSize countStyle:NSByteCountFormatterCountStyleBinary]; 
    NSLog(@"%@", string); 
} 
0

Swift4:

 let attributes = try! FileManager.default.attributesOfItem(atPath: path) 
     let fileSize = attributes[.size] as! NSNumber 
相關問題