Calculating directory size in cocoa

I want to calculate the size of a directory (folder), and I have to list all the files and folders (subfolders) in the volume (disk) with its corresponding size. I use the code below to calculate the size. The problem with this code is the performance issue. I am using NSBrowser to display.

 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; 

Questions:

  • Is there a built-in function?

  • If not the best way to calculate the size?

  • Is it good to use a cache to store the already calculated file size?

Thanks...

+4
source share
2 answers

You can use 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; } 

Take a look at Mac OS X to report directory sizes incorrectly?

+1
source
  1. Is there any built in function available? 

fileSize is a built-in function that gives you size.

  2. If not what is the best way to calculate the size? 

This method is good enough to calculate the size of a folder / directory.

  3. Is it good to use cache to store already calculated file size? 

Yes, you can save it in the cache.

0
source

All Articles