c - opendir:打开的文件太多

标签 c linux file gnu opendir

我编写这段代码来打印 /home/keep 中的所有文件,路径为:

#include <dirent.h>
#include <sys/stat.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

void catDIR(const char *re_path);

int main(int argc, char *argv[])
{
    char *top_path = "/home/keep";
    catDIR(top_path);
    return 0;
}

void catDIR(const char *re_path)
{
    DIR *dp;
    struct stat file_info;
    struct dirent *entry;

    if ((dp = opendir(re_path)) == NULL)
    {
        perror("opendir");
        return;
    }
    while (entry = readdir(dp))
    {
        if (entry->d_name[0] == '.')
            continue;

        //get Absolute path
        char next_path[PATH_MAX];
        strcpy(next_path, re_path);
        strcat(next_path, "/");
        strcat(next_path, entry->d_name);

        lstat(next_path, &file_info);

        if (S_ISDIR(file_info.st_mode))
        {
            catDIR(next_path);
        }
        else
        {
            printf("%s/%s\n", re_path, entry->d_name);
        }
    }
    free(dp);
    free(entry);
}

当我运行它时。

不仅打印了一些文件的路径,还打印了一些错误信息:

opendir:打开的文件过多

我读了 man 3 opendir,然后意识到,我打开了太多文件。

我很想知道,如何关闭它?以及如何更正这个程序

最佳答案

当您完成对目录内容的迭代时,您可能应该使用 closedir

此外,您可能希望将目录列表读入数组,关闭目录,然后递归数组。这可能有助于遍历非常深的目录结构。

关于c - opendir:打开的文件太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10369309/

相关文章:

c - fork() 与 else

linux - QEMU msi 仿真

linux - 使用查找,执行命令并输出到具有原始文件名和附加扩展名的新文件

java 跟踪txt文件内的更改

c - 生成有限制的随机数

c - Linux:通过make而不是c中的#include包含头文件

C: 函数跳过代码中的用户输入

linux - chroot 环境中 bash 脚本中的“意外重定向”

python - 如何使用 Python 2 标准库在 Windows 中检索文件的详细信息

c++ - 从文本文件中的值中减去,然后输出计算 (C++)