gpt4 book ai didi

c - while循环无明显原因停止

转载 作者:行者123 更新时间:2023-12-01 12:45:33 25 4
gpt4 key购买 nike

我有以下 C 代码:

#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>


int main(int argc, const char *argv[]){
const char *directory_path;
directory_path = argv[1];
char *dirname;
dirname = strdup(directory_path);
recursive_ls(dirname);

}


int recursive_ls(char *dirname){
printf("%s\n",dirname);
DIR *d;
struct dirent *dir;

if ((d=opendir(dirname))==-1) {
perror("Oops");
return(0);
}
if(d){
while((dir = readdir(d)) !=NULL){
char *dname = dir->d_name;
puts(dname);
/* if(strcmp(dir->d_type,DT_REG)){
puts("I am a regular file");
} else if(strcmp(dir->d_type,DT_DIR)){
puts("I am a directory.");
recursive_ls(strcat(strcat(dirname,"/"),dir->d_name));
} else {
puts("I am not a file");
}
*/
}

closedir(d);
}
return(0);
}

如果我在 while 循环中注释掉 if(){} else if(){} else(){},我会得到以下输出:

Debug
.project
pipe_test.c
.
..

这是目录中的所有内容。另一方面,如果我取消注释,则会得到以下信息:

/home/wilbert/workspace/pipe_test
.cproject

我认为如果递归步骤搞砸了,我至少应该得到“我不是文件”部分;但是,出于某种原因我不这样做,所以我很困惑。东西编译并没有显示语法错误,所以我真的很困惑。为什么会这样?

最佳答案

由于 Jonathon 建议 d_type 是一个 unsigned char,因此更改为:

if(dir->d_type == DT_REG){
puts("I am a regular file");
} else if(dir->d_type == DT_DIR){
puts("I am a directory.");
recursive_ls(strcat(strcat(dirname,"/"),dir->d_name));
} else {
puts("I am not a file");
}

关于c - while循环无明显原因停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19463112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com