![](/img/trans.png)
[英]Why is my program to calculate Mean square error not giving any output?
[英]Why is my program not displaying any output?
我正在嘗試遞歸遍歷目錄並列出以 .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
,實際上大多數(所有平面內存模型?)編譯器只允許任意指針比較,並且由於您從不取消引用指針,因此您實際上從未嘗試讀取您正在遍歷的未分配地址(如果您這樣做,您最終會出現段錯誤),所以它會永遠持續下去。
我不清楚該循環的目標是什么(也許從“隱藏的”文件名中去除前導.
s ?),所以除了刪除它之外,我真的不能建議修復。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.