我试图显示哪个文件夹包含作为输出。当我在1-2分钟后在硬盘上运行该程序时,它崩溃了,除了崩溃的一部分,它还可以正常工作。我不知道该如何预防。谁能帮我 ?
#include <string.h>
#include <stdio.h>
#include <dirent.h>
void showingFiles(DIR *, char *);
int main(void) {
DIR *folder;
char path[350];
sprintf(path, ".");
folder = opendir(path);
showingFiles(folder, path);
closedir(folder);
printf("\n\nEnter a key to close this program ");
getch();
return 0;
}
void showingFiles(DIR *currentFolder, char *path){
struct dirent *nextFile;
DIR *subFolder;
char copyPath[350];
strcpy(copyPath, path);
while ((nextFile = readdir(currentFolder)) != NULL) {
sprintf(copyPath, "%s//%s", path, nextFile->d_name);
printf("%s\n", (*nextFile).d_name);
if ((strcmp(nextFile->d_name, "..")) &&
strcmp(nextFile->d_name ,".") &&
(subFolder = opendir(copyPath)) != NULL) {
deletingFiles(subFolder, copyPath);
}
}
closedir(currentFolder);
}
您的代码中至少有3个问题可以解释崩溃:
sprintf
来构造它们,可能导致缓冲区溢出。subFolder
在递归函数中打开的目录句柄,这showingFiles
可能会耗尽系统句柄。currentFolder
在函数中关闭了目录句柄showingFiles()
,但在函数中也被关闭了main()
。这会导致未定义的行为。根据经验,始终在打开它的功能中并仅在此位置关闭手柄。不太重要,但存在以下问题:
为showingFiles
执行递归删除整个目录树的功能命名会引起误解。
用双斜杠分隔目录和路径名//
是无用的,并且不可移植。你可能一直在思考的\\
,并转换这个Windows特定目录分隔成//
用于Unix的便携性,但是要知道,单正斜杠是由Windows文件系统处理程序的支持,你应该总是使用/
作为目录分隔符旨在用于Unix和程序视窗。
这是修改后的版本:
#include <dirent.h>
#include <stdio.h>
#include <string.h>
void deleteTree(DIR *, const char *);
int main(void) {
char path[350] = ".";
DIR *folder = opendir(path);
if (folder != NULL) {
deleteTree(folder, path);
closedir(folder);
}
printf("\n\nEnter a key to close this program ");
getch();
return 0;
}
void deleteTree(DIR *currentFolder, const char *path) {
char copyPath[1024];
struct dirent *nextFile;
DIR *subFolder;
while ((nextFile = readdir(currentFolder)) != NULL) {
snprintf(copyPath, sizeof(copyPath), "%s/%s", path, nextFile->d_name);
printf("%s\n", nextFile->d_name);
if (strcmp(nextFile->d_name,"..")
&& strcmp(nextFile->d_name,".")
&& (subFolder = opendir(copyPath)) != NULL) {
deletingFiles(subFolder, copyPath);
closedir(subFolder);
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句