【问题标题】:Directory prwoling recursive functions isn't invoked不调用目录 prwoling 递归函数
【发布时间】:2013-11-29 02:54:27
【问题描述】:

我在制作递归目录列表器时遇到的一个问题是,在递归函数的堆栈中没有调用目录检查后的调用。

void direct_crawl(int indent, char *cwd, STAT nstat)
{
    int i, i_in, count;
    struct direct **files;
    int file_comp();

    count = scandir(cwd, &files, file_comp, alphasort);

    for (i = 0; i < count; i++)
    {
       for (i_in = 0; i_in < indent; i_in++)
            printf("\t");
       printf("%s\n", files[i]->d_name);

       stat(files[i], nstat);

       if (S_ISDIR(nstat->st_mode) != 0)
            direct_crawl(indent + 1, files[i]->d_name, nstat)
     }

}

它上升一个子目录,但如果这些目录有子目录,它就不会打扰......所以,有人可以解释一下我做错了什么吗?谢谢。

【问题讨论】:

  • 你的真实代码是否也错过了错误检查并导致这样的后果?
  • 使用nftw(3)。无需重新发明!

标签: c file recursion directory unistd.h


【解决方案1】:

你做错的是,即使在子目录中你只用一个文件名调用stat(),它是在当前目录而不是子目录中搜索的,所以stat() 失败。如果您在 for 循环之前调用 chdir(cwd) 并在 chdir("..") 之后调用它可能会起作用。

【讨论】:

  • 更好的是,构建(例如使用asprintfsnprintf)文件的完整名称。但总是跳过... 条目。你应该使用nftw
猜你喜欢
  • 2011-11-07
  • 2021-03-30
  • 1970-01-01
  • 1970-01-01
  • 2013-11-06
  • 2018-03-21
  • 2015-03-01
  • 2023-04-04
相关资源
最近更新 更多