C: 使用 nftw 指定最大搜索深度

C: Specify maximum depth of search using nftw

在 C 中,有没有办法指定 nftw 将搜索的基本目录的最大深度?例如,假设我要搜索的目录 dir 有一个子目录,但我只希望 nftw 搜索 subdir 而不是 sub-subdir 或低于该目录的任何内容。

dir
 \_ subdir
    |__ file1
    |__ file2
     \_ sub-subdir
        |__ file1
        |__ file2
         \_ file3

根据手册页 (http://man7.org/linux/man-pages/man3/nftw.3.html),您可以停止从函数参数内部进入子目录。

根据手册中报告的示例,子目录中限制为 2 级,源代码为:

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


// max num of sub dirs
#define MAXLEVEL  2

static int display_info(const char *fpath, const struct stat *sb,
            int tflag, struct FTW *ftwbuf)
{
   // if the depth is above the max sub dirs, continue to next file
   if (ftwbuf->level > MAXLEVEL) {
       return 0; 
   }
   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);
}