简体   繁体   English

使用 nftw 只遍历指定的文件夹

[英]using nftw to only traverse the folder specified

I am using nftw() to do directory traversal.我正在使用nftw()进行目录遍历。 Right now I am only wanting to list out all the files in the directory specified, however it seems to no matter what go down all the folders.现在我只想列出指定目录中的所有文件,但似乎不管 go 下所有文件夹。 It seems that nftw still traverses even if I specify FTW_PHYS .即使我指定FTW_PHYS , nftw 似乎仍然遍历。

The only work around is setting up唯一的解决方法是设置

if (ftwbuf->level > 1) {
    return;
}

in the function that gets called.在被调用的 function 中。 However it is still calling this function on all of these directories.但是,它仍在所有这些目录上调用此 function。

  1. Enable GNU Source before any include directives.在任何 include 指令之前启用 GNU Source。
#define _GNU_SOURCE
  1. Before calling nftw() enable FTW_ACTIONRETVAL in the flags.在调用nftw()之前,在标志中启用FTW_ACTIONRETVAL This enables nftw() to recourse its execution based on return values from callback_function() .这使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);
    }
  1. In the callback_function() at the beginning itself skip the directory if it's above desired level.在开头的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;
}
  1. Whenever nftw() returns with a file in a directory crossing the DEPTH_LIMIT , FTW_SKIP_SIBLINGS instructs it to skip that directory and continue with siblings in parent directory.每当nftw()返回目录中的文件超过DEPTH_LIMIT时, FTW_SKIP_SIBLINGS指示它跳过该目录并继续父目录中的兄弟文件。

  2. If you omit FTW_DEPTH in nftw() flags , you can use FTW_SKIP_SUBTREE feature;如果在nftw() flags中省略FTW_DEPTH ,则可以使用FTW_SKIP_SUBTREE功能; where nftw() skips a directory right away. nftw()跳过一个目录。

    • FTW_DEPTH instructs nftw() to pass the directory itself after going through all files & sub-directories in it. FTW_DEPTH指示nftw()在遍历目录中的所有文件和子目录传递目录本身。 This post-order traversal of directories makes it difficult to use FTW_SKIP_SUBTREE ;这种目录post-order遍历使得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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM