1. 程式人生 > >linux遍歷資料夾(目錄樹)nftw

linux遍歷資料夾(目錄樹)nftw

http://www.cnblogs.com/harlanc/p/6991041.html

#define _XOPEN_SOURCE 500
#include <ftw.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
/*
http://www.cnblogs.com/harlanc/p/6991041.html


FTW_F fpath是一個普通檔案。
FTW_D fpath是一個目錄。
FTW_DNR fpath是一個不能被讀的目錄。
FTW_DP fpath是一個目錄,並且 flag引數被指定為FTW_DEPTH。(如果flags沒有被指定為FTW_DEPTH,
那麼訪問目錄時使用的typeflag總會是FTW_D。)路徑fpath下的所有檔案和子目錄已經被處理過了。


FTW_NS 在不是符號連結的fpath上呼叫stat失敗。可能的原因是呼叫者對父目錄有讀許可權,
所以檔名fpath可以被看到,但是沒有執行許可權,所以執行stat失敗。由sb指向的快取的內容是未定義的。


FTW_SL fpath是一個符號連結,flags被設定為FTW_PHYS。
FTW_SLN fpath是一個指向不存在的檔案的符號連結。(只在FTW_PHYS未被設定的時候才會發生。)


struct FTW 
{
   int base;
   int level;
};


*/
static int
display_info(const char *fpath, const struct stat *sb,
             int tflag, struct FTW *ftwbuf)
{
    printf("%-3s %2d ",
            (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);


    if (tflag == FTW_NS)//連結檔案
        printf("-------");
    else
        printf("%7jd", (intmax_t) sb->st_size);


    printf("   %-40s %d %s\n",
            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);
}