LoginSignup
9
9

More than 5 years have passed since last update.

FTSを用いたファイルの高速一括処理

Last updated at Posted at 2014-02-17

ディレクトリ配下の総ファイルサイズを計算する 〜 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];
9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9