Objective c 获取给定路径的文件大小

Objective c 获取给定路径的文件大小,objective-c,macos,path,filesize,Objective C,Macos,Path,Filesize,我是objective-c的新手。 我有一个包含在NSString中的文件路径,我想获得文件大小。我发现了这一点,并用attributesFiteMatPath:error:更改了不推荐使用的代码,但路径始终无效 NSFileManager *fileManager = [[NSFileManager alloc] init]; NSString *path = @"~/Library/Safari/History.plist"; NSDictionary *fileAttributes = [

我是objective-c的新手。 我有一个包含在NSString中的文件路径,我想获得文件大小。我发现了这一点,并用attributesFiteMatPath: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];

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

 - (NSString *)stringByExpandingTildeInPath

在NSFileManager上使用
defaultManager
类方法,而不是创建自己的实例。另外,不要在文件路径中包含
~
(tilde)符号。使用
NSHomeDirectory()
函数获取主目录。下面是一个例子:

NSString *path = [NSString stringWithFormat:@"%@/Library/Safari/History.plist", NSHomeDirectory()];
[[[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil] fileSize];
这将返回文件的大小。

这应该可以:

uint64_t fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:_filePath error:nil] fileSize];
它与您使用的非常相似,但在您的中有一个错误:您在
错误:
处理中放置了
NULL
而不是
nil

还要确保在路径中展开平铺,如:use
stringByExpandingTildeInPath
中所述,因此您的
NSString*path
应该如下所示:

NSString *path = [[NSString stringWithString:@"~/Library/Safari/History.plist"] stringByExpandingTildeInPath];
您可以找到有关
nil
NULL
之间差异的一些解释。您可以通过以下方式获得大小:

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

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

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

改变

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


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

我认为问题不在于tilde(~),而在于NSString*path=@“which.txt”;代码不起作用。您是否尝试过在错误处理中使用
nil
而不是
NULL
?我发布的代码已经在我的一些应用程序中进行了测试和使用,所以我确信它是有效的。尝试使用完整路径,例如/Users/USERNAME/Library/Safari/History.plist,并使用
NSFileManager
defaultMangaer
创建自己的实例。我写了一段代码,它符合您的要求:经过测试,它可以工作。我尝试了nil,没有错误,但代码不工作。在控制台中,我尝试了您的代码,这是确定的,但我可以需要输入您的用户名。我怎么能不说呢?仅限/Library/Safari/History.plist?您不需要输入用户名就可以找到代码。如果没有NSDictionary*fileAttributes,其余代码将无法工作。Ok,不使用~例如NSString*path=@“which.txt”;NSDictionary*fileAttributes=[fileManager AttributesFiteMatPath:路径错误:NULL];代码不再工作。此方法的级别过低。我喜欢:)比stringWithFormat和NSHomeDirectory()更简单、更可读。
if (fileSize = [fileAttributes objectForKey:NSFileSize]) {