我的任務是重新制作 find 命令的部分功能。我要做的第一部分只是普通的“查找”,它列出了該目錄中的所有檔案和子目錄。我正在使用實際的 find 命令來測驗我的結果。
任何明顯的我遺漏的東西導致我列印不正確的檔案路徑?
圖片順序:
C代碼
預期產出
實際輸出
我用來測驗的目錄的樹
void readSub (char* subDir) { DIR *sub_dp = opendir(subDir); //Opens directory stream struct dirent *subDirp; //define sub directory pointer struct stat buf; //define file status struct char t1[] = "."; char t2[] = ".."; char t3[] = "/"; if(sub_dp != NULL) // Was directory successfully opened { //read each entry one time only while((subDirp = readdir(sub_dp)) != NULL) { char *temp = subDirp -> d_name; //check if first entry was a sub directory //avoid searching for . and .. if(strcmp(temp, t1) != 0 && strcmp(temp, t2) != 0) { char *tempSub = t3; tempSub = strcat(tempSub, temp); //add / to entry name char *temp_full_path = malloc(sizeof(char) * 2000); temp_full_path = strcpy(temp_full_path, subDir); strcat(temp_full_path, tempSub); //gives full path printf("%s\n", temp_full_path); DIR *subsubDP = opendir(temp_full_path); //try to open if(subsubDP != NULL) //if not NULL then subsubDP is sub directory { closedir(subsubDP); //will get opened in recursive call readSub(temp_full_path); //recursive call } } } //end of while loop closedir(sub_dp); //close directory stream } else { printf("Can't open directory\n"); exit(2); } } int main(int argc, char **argv) { char *dir; if(argc < 2) { dir = "."; } else { dir = argv[1]; } readSub(dir); exit(0); }



uj5u.com熱心網友回復:
問題是
tempSub = strcat(tempSub, temp); //add / to entry name
tempSub指向t3只有 2 個位元組的陣列。連接temp到它會在陣列邊界之外寫入,這會導致未定義的行為。
您應該通過將, , ,temp_full_path的長度加上空終止符的長度來計算總長度,然后分配它。由于您只需要在當前回圈迭代中使用它,因此您可以使用可變長度陣列而不是(您的代碼從不呼叫)。subDirt3tempmalloc()free(temp_full_path)
代替
char *tempSub = t3;
tempSub = strcat(tempSub, temp); //add / to entry name
char *temp_full_path = malloc(sizeof(char) * 2000);
temp_full_path = strcpy(temp_full_path, subDir);
strcat(temp_full_path, tempSub); //gives full path
和
char temp_full_path[strlen(subDir) strlen(t3) strlen(temp) 1];
sprintf(temp_full_path, "%s%s%s", subDir, t3, temp);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/467396.html
上一篇:為什么strcpy(buffer i,buffer i 1)與使用臨時陣列的方式不同?
下一篇:連接兩個字串的C程式
