4

ディレクトリ(フォルダ)のサイズを計算したいのですが、ボリューム(ドライブ)内のすべてのファイルとフォルダ(サブフォルダ)を対応するサイズで一覧表示する必要があります。次のコードを使用してサイズを計算しています。このコードの問題は、パフォーマンスの問題。を表示するために使用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;

質問:

  1. 組み込み機能はありますか?

  2. そうでない場合、サイズを計算するための最良の方法は何ですか?

  3. 計算済みのファイルサイズを保存するためにキャッシュを使用するのは良いですか?

ありがとう...

4

2 に答える 2

1

使用できます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;

}

Mac OS X がディレクトリ サイズを正しく報告していないことを確認してください。

于 2013-02-21T09:44:52.850 に答える
0
  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?

はい、キャッシュに保存できます。

于 2013-02-21T09:02:15.673 に答える