[英]calculating directory size in cocoa
我想計算目錄(文件夾)大小,我必須列出其相應大小的卷(驅動器)中的所有文件和文件夾(子文件夾)。我使用下面的代碼來計算大小。此代碼的問題是性能問題。 我正在使用NSBrowser
進行顯示。
NSArray *filesArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:folderPath error:nil];
NSEnumerator *filesEnumerator = [filesArray objectEnumerator];
NSString *fileName;
unsigned long long int fileSize = 0;
while (fileName = [filesEnumerator nextObject])
{
NSDictionary *fileDictionary = [[NSFileManager defaultManager] attributesOfItemAtPath:folderPath error:nil];
fileSize += [fileDictionary fileSize];
}
return fileSize;
問題:
有內置功能嗎?
如果不是,計算尺寸的最佳方法是什么?
使用緩存來存儲已經計算的文件大小是否合適?
謝謝...
你可以使用stat
。
-(unsigned long long)getFolderSize : (NSString *)folderPath;
{
char *dir = (char *)[folderPath fileSystemRepresentation];
DIR *cd;
struct dirent *dirinfo;
int lastchar;
struct stat linfo;
static unsigned long long totalSize = 0;
cd = opendir(dir);
if (!cd) {
return 0;
}
while ((dirinfo = readdir(cd)) != NULL) {
if (strcmp(dirinfo->d_name, ".") && strcmp(dirinfo->d_name, "..")) {
char *d_name;
d_name = (char*)malloc(strlen(dir)+strlen(dirinfo->d_name)+2);
if (!d_name) {
//out of memory
closedir(cd);
exit(1);
}
strcpy(d_name, dir);
lastchar = strlen(dir) - 1;
if (lastchar >= 0 && dir[lastchar] != '/')
strcat(d_name, "/");
strcat(d_name, dirinfo->d_name);
if (lstat(d_name, &linfo) == -1) {
free(d_name);
continue;
}
if (S_ISDIR(linfo.st_mode)) {
if (!S_ISLNK(linfo.st_mode))
[self getFolderSize:[NSString stringWithCString:d_name encoding:NSUTF8StringEncoding]];
free(d_name);
} else {
if (S_ISREG(linfo.st_mode)) {
totalSize+=linfo.st_size;
} else {
free(d_name);
}
}
}
}
closedir(cd);
return totalSize;
}
1. Is there any built in function available?
fileSize
是一個內置函數,可以為您提供大小。
2. If not what is the best way to calculate the size?
此方法足以計算文件夾/目錄的大小。
3. Is it good to use cache to store already calculated file size?
是的,您可以將其存儲在緩存中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.