[英]Why is my program not displaying any output?
I am trying to recursively traverse through a directory and list any files that end in .txt or the names of folders.我正在尝试递归遍历目录并列出以 .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);
}
My expected results would be the files that end in .txt and files that are folders.我的预期结果是以 .txt 结尾的文件和作为文件夹的文件。 However, the output is blank and it may go into an infinite loop.
但是,输出为空白,并且可能进入无限循环。
This is an infinite loop:这是一个无限循环:
while (name != "." || name != NULL) {
name++;
}
name
is a char*
. name
是一个char*
。 Unless the interned string literal "."
除非实习字符串文字
"."
is stored at the NULL
address (it isn't), then you're saying the loop should continue forever, because name
will always be either not pointing to the storage for "."
存储在
NULL
地址(不是),然后您说循环应该永远继续,因为name
将始终不指向"."
的存储"."
or not pointing to NULL
.或不指向
NULL
。 While I believe it's officially undefined behavior to compare unrelated pointers like "."
虽然我认为比较像
"."
这样不相关的指针是官方未定义的行为"."
and name
, in practice most (all flat memory model?) compilers just allow arbitrary pointer comparisons, and since you never dereference the pointer, you never actually try to read the unallocated addresses you're traversing (you'd eventually segfault if you did), so it just goes on forever.和
name
,实际上大多数(所有平面内存模型?)编译器只允许任意指针比较,并且由于您从不取消引用指针,因此您实际上从未尝试读取您正在遍历的未分配地址(如果您这样做,您最终会出现段错误),所以它会永远持续下去。
I'm unclear on what the goal of that loop is (maybe stripping leading .
s from "hidden" file names?), so I can't really suggest a fix other than removing it.我不清楚该循环的目标是什么(也许从“隐藏的”文件名中去除前导
.
s ?),所以除了删除它之外,我真的不能建议修复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.