我正在尝试遍历给定路径的目录,但以下程序不会进入目录内部并陷入无限循环。这段代码有什么问题:
void func(char path[]);
int main(int argc, char *argv)
{
char buf[255];
getcwd(buf,255);
func(buf);
}
void func(char path[])
{
DIR *dirp;
struct stat states;
struct dirent *direntp;
dirp=opendir(path);
chdir(path);
while((direntp=readdir(dirp))!=NULL)
{
if(S_ISDIR(states.st_mode))//true than returns zero
{
printf("%s\n",direntp->d_name);
}
else
if(!(strcmp(direntp->d_name,".")||strcmp(direntp->d_name,"..")))// if true retrns zero
{
continue;
}
else
{
func(direntp->d_name);
chdir("..");
}
}
}
最佳答案
您可能缺少一些代码,或者问题是您从未填充/更新状态
。
再看看这一行:
if(!(strcmp(direntp->d_name,".")||strcmp(direntp->d_name,"..")))
它永远不会计算为真值,因为这需要 direntp->d_name
等于 .
和 ..
同时(这根本不可能)。我猜您想在此处检查 &&
,只有在您的目录名称与任一值匹配的情况下,它才会进入分支。
关于c - 遍历C中的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13855932/