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

时间:2009-05-02 19:43:12

标签: objective-c cocoa macos

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

10 个答案:

答案 0 :(得分:132)

这个班轮可以帮助人们:

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

以字节为单位返回文件大小。

答案 1 :(得分:74)

请记住,自Mac OS X v10.5起,不推荐使用fileAttributesAtPath:traverseLink:。请改用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 :(得分:17)

如果有人需要Swift版本:

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

答案 3 :(得分:12)

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);

答案 4 :(得分:6)

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

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

答案 5 :(得分:6)

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

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

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);
}

答案 6 :(得分:2)

Swift 2.2:

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

答案 7 :(得分:1)

它将以字节...给文件大小

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

答案 8 :(得分:0)

Swift4:

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

答案 9 :(得分:0)

在Swift 3.x及更高版本中,您可以使用:

do {
    //return [FileAttributeKey : Any]
    let attr = try FileManager.default.attributesOfItem(atPath: filePath)
    fileSize = attr[FileAttributeKey.size] as! UInt64

    //or you can convert to NSDictionary, then get file size old way as well.
    let attrDict: NSDictionary = try FileManager.default.attributesOfItem(atPath: filePath) as NSDictionary
    fileSize = dict.fileSize()
} catch {
    print("Error: \(error)")
}