如果我只需要知道文件是文件夹/符号链接及其大小,是否可以使用更快的文件系统API。我目前正在使用[NSFileManager attributesOfItemAtPath ...]并且只使用NSFileSize和NSFileType。
我应该使用哪些批量文件系统枚举API?我怀疑这可以更快,而不必跳出用户代码。
我的目标是快速递归目录以获取文件夹真实文件大小,并且当前调用attributesOfItemAtPath是我95%的瓶颈。
我目前正在使用的一些代码:
NSDictionary* properties = [fileManager attributesOfItemAtPath:filePath error:&error];
long long fileSize = [[properties objectForKey:NSFileSize] longLongValue];
NSObject* fileType = [[properties objectForKey:NSFileType isEqual:NSFileTypeDirectory];
答案 0 :(得分:3)
如果你想变得非常毛茸茸,Mac OS内核会实现一个独特的getdirentriesattr()
系统调用,该调用将返回指定目录中的文件和属性列表。设置和调用很麻烦,所有文件系统(!)都不支持它,但是如果你能让它为你工作,它可以显着加快速度。
还有一个密切相关的searchfs()
系统调用,可用于快速搜索文件。它受制于大多数相同的陷阱。
答案 1 :(得分:1)
是否更快我不确定,但NSURL
会通过getResourceValue:forKey:error:
NSError * e;
NSNumber * isDirectory;
BOOL success = [URLToFile getResourceValue:&isDirectory
forKey:NSURLIsDirectoryKey
error:&e];
if( !success ){
// error
}
NSNumber * fileSize;
BOOL success = [URLToFile getResourceValue:&fileSize
forKey:NSURLFileSizeKey
error:&e];
如果你真的不关心这个错误,你可能也会觉得把它包起来很方便:
@implementation NSURL (WSSSimpleResourceValueRetrieval)
- (id)WSSResourceValueForKey: (NSString *)key
{
id value = nil;
BOOL success = [self getResourceValue:&value
forKey:key
error:nil];
if( !success ){
value = nil;
}
return value;
}
@end
这是作为已弃用的文件管理器功能FSGetCatalogInfo()
的替代品,它在an old Cocoa-dev thread的Dave DeLong gives the thumbs up to的解决方案中使用。
对于枚举部分,“文件系统编程指南”有一个"Getting the Contents of a Directory in a Single Batch Operation"部分,其中讨论了使用contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error:
答案 2 :(得分:1)
您可以使用stat和lstat
。请查看this answer以计算目录大小
CPU raises with attributesOfItemAtPath:error: