在c中显示文件夹内容 - 运行时错误

时间:2017-02-18 19:20:23

标签: c runtime-error dirent.h

我试图显示哪个文件夹包含输出。当我在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);
}

1 个答案:

答案 0 :(得分:1)

您的代码中至少有3个问题可以解释崩溃:

  • 用于存储完整路径名的缓冲区支付的时间太短,并且使用不安全的sprintf来构造它们,可能会导致缓冲区溢出。
  • 您永远不会关闭在递归函数subFolder中打开的showingFiles目录句柄,可能会耗尽系统句柄。
  • 您关闭了函数currentFolder中的目录句柄showingFiles(),但在main()函数中也关闭了。{li>这会导致未定义的行为。根据经验,始终关闭打开它的函数中的句柄,并且仅在那里。

不太重要但问题:

  • 要命名showingFiles,执行递归删除完整目录树的函数有点误导。

  • 使用双斜杠//分隔目录和路径名是无用的,不可移植。您可能一直在考虑\\并将此特定于Windows的目录分隔符转换为//以获取Unix可移植性,但请注意Windows文件系统处理程序支持单个正斜杠 对于你应该始终使用/作为针对Unix和Windows的程序的目录分隔符。

以下是修改后的版本:

#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);
        }
    }
}
相关问题