我正在使用nftw()进行目录遍历。现在,我只想列出指定目录中的所有文件,但是似乎不管所有文件夹下的是什么文件。即使我指定了FTW_PHYS,似乎nftw仍然遍历。
周围唯一的工作就是设置
if (ftwbuf->level > 1) {
return;
}在调用的函数中。但是,它仍在所有这些目录上调用此函数。
发布于 2022-04-08 15:56:03
#define _GNU_SOURCE在调用
FTW_ACTIONRETVAL。这使nftw()能够根据来自callback_function().的返回值追索其执行。
/* snippet from nftw manpage */
#define MAX_OPEN_FDS 64
flags |= FTW_ACTIONRETVAL; // enables callback_function() to recourse
if (nftw ((argc < 2) ? "." : argv[1], callback_function, MAX_OPEN_FDS, flags)
== -1) {
perror ("nftw");
exit (EXIT_FAILURE);
}如果目录高于所需的级别,则
callback_function()开始时跳过目录。#define DEPTH_LIMIT 1
/*
...
*/
int
callback_function (const char *fpath, const struct stat *sb,
int tflag, struct FTW *ftwbuf) {
// works even when FTW_DEPTH is enabled.
// at the top first condition to check;
if (ftwbuf->level > DEPTH_LIMIT) return FTW_SKIP_SIBLINGS;
/*
...
*/
return FTW_CONTINUE;
}每当
DEPTH_LIMIT的目录中的文件时,FTW_SKIP_SIBLINGS指示它跳过该目录并继续与父目录中的兄弟姐妹在一起。如果您省略了
FTW_DEPTH,则可以使用FTW_SKIP_SUBTREE功能;nftw()将跳过一个目录。- `FTW_DEPTH` instructs `nftw()` to pass the directory itself **after** going through all files & sub-directories in it. This `post-order` traversal of directories makes it difficult to use `FTW_SKIP_SUBTREE`;// without `FTW_DEPTH` in nftw-flags
int
callback_function (const char *fpath, const struct stat *sb,
int tflag, struct FTW *ftwbuf) {
/*
...
*/
if (DEPTH_LIMIT == ftwbuf->level && FTW_D == tflag) // a directory
return FTW_SKIP_SUBTREE; // don't get into the directory
else
return FTW_CONTINUE;
}https://stackoverflow.com/questions/71797970
复制相似问题