首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C:使用nftw指定最大搜索深度

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

Stack Overflow用户
提问于 2015-11-20 20:37:16
回答 2查看 3.4K关注 0票数 1

在C中,是否有一种方法可以指定nftw将搜索的基目录的最大深度?例如,假设我要搜索的目录dir有一个子目录,但是我只希望nftw通过subdir搜索,而不是通过sub-subdir搜索,或者在它下面的任何东西。

代码语言:javascript
复制
dir
 \_ subdir
    |__ file1
    |__ file2
     \_ sub-subdir
        |__ file1
        |__ file2
         \_ file3
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-11-20 21:07:58

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

从手册中报告的示例(子目录中限制为2级)来看,源代码是:

代码语言:javascript
复制
#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);
}
票数 2
EN

Stack Overflow用户

发布于 2022-10-29 20:15:00

如果您不介意使用glibc特定的实现,那么将FTW_ACTIONRETVAL添加到nftw()的第四个参数中,然后在回调中返回FTW_SKIP_SIBLINGS (而不是0),如果ftw->level的深度超过您的深度。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33835652

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档