在C中,是否有一种方法可以指定nftw将搜索的基目录的最大深度?例如,假设我要搜索的目录dir有一个子目录,但是我只希望nftw通过subdir搜索,而不是通过sub-subdir搜索,或者在它下面的任何东西。
dir
\_ subdir
|__ file1
|__ file2
\_ sub-subdir
|__ file1
|__ file2
\_ file3发布于 2015-11-20 21:07:58
根据手册页面(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);
}发布于 2022-10-29 20:15:00
如果您不介意使用glibc特定的实现,那么将FTW_ACTIONRETVAL添加到nftw()的第四个参数中,然后在回调中返回FTW_SKIP_SIBLINGS (而不是0),如果ftw->level的深度超过您的深度。
https://stackoverflow.com/questions/33835652
复制相似问题