如何获得给定路径的文件大小?

hek*_*ran 67 macos cocoa objective-c

我有一个包含在NSString中的文件路径.有没有办法获得其文件大小?

Ode*_*Dov 133

这个班轮可以帮助人们:

unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:someFilePath error:nil] fileSize];
Run Code Online (Sandbox Code Playgroud)

这将以字节为单位返回文件大小.

  • bytes - 测量值是字节 (7认同)
  • 该方法的实际返回值是`unsigned long long`,因此`int`不适合在这里. (3认同)
  • 我喜欢这一个.但这是什么衡量标准?字节,Kb等?也谢谢你. (2认同)

Fra*_*rar 74

请记住,自Mac OS X v10.5起,不推荐使用fileAttributesAtPath:traverseLink:.attributesOfItemAtPath:error:相反,请使用相同网址描述的相同内容.

有一点需要注意,我是Objective-C的新手,而且我忽略了调用时可能出现的错误attributesOfItemAtPath:error:,你可以执行以下操作:

NSString *yourPath = @"Whatever.txt";
NSFileManager *man = [NSFileManager defaultManager];
NSDictionary *attrs = [man attributesOfItemAtPath: yourPath error: NULL];
UInt32 result = [attrs fileSize];
Run Code Online (Sandbox Code Playgroud)

  • 此代码泄漏分配的FileManager.我建议您只使用NSFileManager.defaultManager Singleton来避免这种情况. (2认同)

Tyl*_*ong 17

如果有人需要Swift版本:

let attr: NSDictionary = try! NSFileManager.defaultManager().attributesOfItemAtPath(path)
print(attr.fileSize())
Run Code Online (Sandbox Code Playgroud)


Par*_*fna 12

CPU使用attributesOfItemAtPath引发:错误:
您应该使用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);
Run Code Online (Sandbox Code Playgroud)


Sk *_*din 7

如果只想使用带字节的文件大小,

unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:yourAssetPath error:nil] fileSize];
Run Code Online (Sandbox Code Playgroud)

NSByteCountFormatter文件大小的字符串转换(来自字节)具有精确的KB,MB,GB ...它的返回像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);
}
Run Code Online (Sandbox Code Playgroud)


Apo*_*llo 6

根据Oded Ben Dov的回答,我宁愿在这里使用一个对象:

NSNumber * mySize = [NSNumber numberWithUnsignedLongLong:[[[NSFileManager defaultManager] attributesOfItemAtPath:someFilePath error:nil] fileSize]];
Run Code Online (Sandbox Code Playgroud)