ディレクトリ配下の総ファイルサイズを計算する 〜 BSDのftsを使うを参考にしながら、ftsを用いて大量のファイルを一気に処理するロジックを作成します。ftsの構造体をそのまま使った方がパフォーマンスが出るので、シンプルに処理をブロックとして切り出すインタフェイスにしてみました。
#include <sys/types.h>
#include <sys/stat.h>
#include <fts.h>
- (void)traverseURL : (NSURL*) url
fileBlock : (void (^)(FTSENT *entry))fileBlock
dirBlock : (void (^)(FTSENT *entry))dirBlock
{
const char *cPath = [url.path cStringUsingEncoding:NSUTF8StringEncoding];
int l = strlen(cPath);
char *path = calloc(l, sizeof(char));
strncpy(path, cPath, l);
char * const paths[] = {
path, NULL
};
FTS* fts = fts_open(paths, 0, NULL);
FTSENT *entry;
while ((entry = fts_read(fts))) {
if (entry->fts_info & FTS_D) {
// Directory in Pre-Order
if(dirBlock){
dirBlock(entry);
}
}
else if (entry->fts_info & FTS_F) {
// Regular File
if(fileBlock){
fileBlock(entry);
}
}
}
fts_close(fts);
free(path);
}
たとえば、ファイルサイズの合計を取得したい場合には下記のようになります。シンプル!
__block off_t totalSize = 0;
[self traverseURL:url
fileBlock:^(FTSENT *entry) {
totalSize += entry->fts_statp->st_size;
} dirBlock:nil];