我的C函数遍历系统目录,而segfaults遍历大型输入。我该如何解决?

问题描述 投票:0回答:1

我正在尝试编写一个程序,该程序可搜索给定目录及其中的所有子目录和文件(以及子目录的子目录和文件等),并打印出具有给定目录的所有文件。权限集(int target_perm)。

它在较小的输入上运行良好,但是当它必须在具有大量文件的目录上递归时返回Segmentation fault (core dumped)。 Valgrind揭示这是由于堆栈溢出造成的。

有什么办法可以修复我的功能,使其可以与任意大目录一起使用?

void recurse_dir(struct stat *sb, struct dirent *de, DIR *dr, int target_perm, char* curr_path) {
    if ((strcmp(".", de->d_name) != 0) && (strcmp("..", de->d_name) != 0)) {

        char full_file_name[strlen(curr_path) + strlen(de->d_name)+1];
        strcpy(full_file_name, curr_path);
        strcpy(full_file_name + strlen(curr_path), de->d_name);
        full_file_name[strlen(curr_path) + strlen(de->d_name)] = '\0';

        if (stat(full_file_name, sb) < 0) {
            fprintf(stderr, "Error: Cannot stat '%s'. %s\n", full_file_name, strerror(errno));
        } else {
            char* curr_perm_str = permission_string(sb);
            int curr_perm = permission_string_to_bin(curr_perm_str);
            free(curr_perm_str);

            if ((curr_perm == target_perm )) {
                printf("%s\n", full_file_name);
            }

            if (S_ISDIR(sb->st_mode)) {
                DIR *dp;
                struct dirent *dent;
                struct stat b;
                dp = opendir(full_file_name);

                char new_path[PATH_MAX];
                strcpy(new_path, full_file_name);
                new_path[strlen(full_file_name)] ='/';
                new_path[strlen(full_file_name)+1] ='\0';

                if (dp != NULL) {
                    if ((dent = readdir(dp)) != NULL) {
                        recurse_dir(&b, dent, dp, target_perm, new_path);
                    }
                    closedir(dp);               
                } else {
                    fprintf(stderr, "Error: Cannot open directory '%s'. %s.\n", de->d_name, strerror(errno));
                }
            }           
        }
    }

    if ((de = readdir(dr)) != NULL) {
        recurse_dir(sb, de, dr, target_perm, curr_path);
    }
}
c recursion segmentation-fault stack-overflow directory-structure
1个回答
0
投票

这里的问题实际上不是递归,尽管我已经在下面解决了这个特定问题。问题在于您的目录层次结构可能包含符号链接,这些符号链接为其父目录之一添加了一些目录别名。来自Ubuntu安装的示例:

© www.soinside.com 2019 - 2024. All rights reserved.