获取给定路径的文件大小

时间:2012-01-02 09:31:20

标签: objective-c macos path filesize

我是Objective-c的新手。 我有一个包含在NSString中的文件路径,我想要获取文件大小。我找到了这个example并使用attributesOfItemAtPath更改了已弃用的代码:error:但路径始终无效。

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

5 个答案:

答案 0 :(得分:4)

这应该有效:

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

它与您使用的非常相似,但是在您的错误中:您在NULL处理中放置了nil而不是error:

请确保在路径中展开代字号,如documentation中所述:使用stringByExpandingTildeInPath,因此您的NSString *path应该是这样的:

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

Here您可以找到有关nilNULL之间差异的一些解释。

答案 1 :(得分:1)

您可能需要使用以下方法展开路径:

 - (NSString *)stringByExpandingTildeInPath

答案 2 :(得分:1)

你可以通过以下方式获得尺寸:

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

size是包含无符号长long的NSNumber。

答案 3 :(得分:1)

由于代码中存在超级愚蠢的错误,您的路径始终无效。

更改

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

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

我希望不需要进一步解释。

答案 4 :(得分:0)

在NSFileManager上使用defaultManager类方法,而不是创建自己的实例。此外,请勿在文件路径中包含~(代字号)符号。使用NSHomeDirectory()函数来获取主目录。这是一个例子:

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

这应该返回文件的大小。

相关问题