gpt4 book ai didi

c - 为什么我的程序不显示任何输出?

转载 作者:行者123 更新时间:2023-11-30 19:27:48 25 4
gpt4 key购买 nike

我正在尝试递归遍历目录并列出以 .txt 或文件夹名称结尾的所有文件。

void listFilesRecursively(char *basePath) {

char path[1000];
struct dirent *ptr;
DIR *dir = opendir(basePath);

// Unable to open directory
if (!dir)
return;

while ((ptr = readdir(dir)) != NULL)
{
if (strcmp(ptr->d_name,".") != 0 && strcmp(ptr->d_name, "..") != 0)
{

char *name = NULL;
char *type = NULL;

while (name != "." || name != NULL) {
name++;
}

for (name = ptr->d_name; *name != '\0' ; name++) {

if (name == '.') {
while (*name != '\0') {
*type = *name;
name++;
}
break;

} else if (*name == '\0') {
printf("%s\n", ptr->d_name);
}

}

if (strcmp(type,"txt") == 0)
printf("%s\n", ptr->d_name);

// create new path from our base path
strcpy(path, basePath);
strcat(path, "/");
strcat(path, ptr->d_name);

listFilesRecursively(path);

}
}
closedir(dir);
}

我的预期结果是以 .txt 结尾的文件和文件夹文件。但是,输出是空白的,并且可能会进入无限循环。

最佳答案

这是一个无限循环:

        while (name != "." || name != NULL) {
name++;
}

name 是一个 char*。除非内部字符串文字 "." 存储在 NULL 地址(事实并非如此),否则您会说循环应该永远继续下去,因为 name 始终要么不指向 "." 的存储,要么不指向 NULL。虽然我认为比较 "."name 等不相关指针是官方未定义的行为,但实际上大多数(所有平面内存模型?)编译器只允许任意指针比较,并且因为您从不取消引用指针,所以您实际上从未尝试读取正在遍历的未分配地址(如果这样做,最终会出现段错误),因此它会永远持续下去。

我不清楚该循环的目标是什么(也许从“隐藏”文件名中剥离前导 . ?),所以除了删除它之外,我真的无法建议修复.

关于c - 为什么我的程序不显示任何输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55388414/

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