echo Impossible|sed 's/Im/To be /'

October 26, 2010

Tip. File tree walk

在 Unix 上走遍目錄樹


這幾日看了幾個人寫的走目錄樹找檔案的方法,感想是難到沒有比較容易的方法嗎? 何苦一定要自已刻呢? Google 及 man 了一下果然有答案。


C 的方法 nftw ftw ,截錄 man ftw 的範例

#define _XOPEN_SOURCE 500
#include <ftw.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

static int
display_info(const char *fpath, const struct stat *sb,
             int tflag, struct FTW *ftwbuf)
{
    printf("%-3s %2d %7jd   %-40s %d %s\n",
        (tflag == FTW_D) ?   "d"   : (tflag == FTW_DNR) ? "dnr" :
        (tflag == FTW_DP) ?  "dp"  : (tflag == FTW_F) ?   "f" :
        (tflag == FTW_NS) ?  "ns"  : (tflag == FTW_SL) ?  "sl" :
        (tflag == FTW_SLN) ? "sln" : "???",
        ftwbuf->level, (intmax_t) sb->st_size,
        fpath, ftwbuf->base, fpath + ftwbuf->base);
    return 0;           /* To tell nftw() to continue */
}

int
main(int argc, char *argv[])
{
    int flags = 0;

    if (argc > 2 && strchr(argv[2], 'd') != NULL)
        flags |= FTW_DEPTH;
    if (argc > 2 && strchr(argv[2], 'p') != NULL)
        flags |= FTW_PHYS;

    if (nftw((argc < 2) ? "." : argv[1], display_info, 20, flags)
            == -1) {
        perror("nftw");
        exit(EXIT_FAILURE);
    }
    exit(EXIT_SUCCESS);
}

Python os.walk 的方法

#!/usr/bin/python
import os

for root, dirs, files in os.walk ("/etc") :
    for i in files :
        print root, i, "<-- FILE"
    for i in dirs :
        print root, i, "<-- DIR"

Python 上另一個用 Generator 的方法

#!/usr/bin/python
from __future__ import generators

import os, sys

def dirwalk(dir):
    "walk a directory tree, using a generator"
    try:
        for f in os.listdir(dir):
            fullpath = os.path.join(dir,f)
            if os.path.isdir(fullpath) and not os.path.islink(fullpath):
                for x in dirwalk(fullpath):  # recurse into subdir
                    yield x
            else:
                yield fullpath
    except OSError:
        pass

if __name__ == "__main__":
    a = dirwalk ("/etc")
    for i in a:
        print i