C 使用递归函数的目录是';t调用

C 使用递归函数的目录是';t调用,c,file,recursion,directory,unistd.h,C,File,Recursion,Directory,Unistd.h,我在创建递归目录列表器时遇到的一个问题是,在递归函数的堆栈中没有调用目录检查后的调用 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

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

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)
     }
void direct\u crawl(int缩进、char*cwd、STAT nstat)
{
int i,i_in,count;
结构直接**文件;
int file_comp();
计数=scandir(cwd、文件和文件、文件组、字母排序);
对于(i=0;id\u名称);
stat(文件[i],nstat);
如果(S_ISDIR(nstat->st_模式)!=0)
直接_爬网(缩进+1,文件[i]>d_名称,nstat)
}
}


它上升一个子目录,但如果这些目录有子目录,它就不麻烦了…所以,有人能解释一下我做错了什么吗?谢谢。

你做错了的是,即使在子目录中,你调用的
stat()
也只有一个文件名,该文件名在当前目录中搜索,而不是在子目录中,因此
stat()
失败。如果您在
for
循环之前和之后调用
chdir(cwd)
,则可能会起作用。

您的真实代码是否也会错过错误检查,从而导致此类后果?请使用。不需要重新发明它!更好的是,构建文件的完整名称(例如,使用
asprintf
snprintf
)。但始终跳过
&
条目。您应该使用
nftw