首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >opendir:打开的文件太多

opendir:打开的文件太多
EN

Stack Overflow用户
提问于 2012-04-29 10:50:14
回答 2查看 3.4K关注 0票数 1

我编写此代码以打印/home/keep中包含绝对路径的所有文件:

代码语言:javascript
复制
#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: Too many open files

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

我确实想知道,如何关闭它?以及如何纠正这个程序

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-04-29 10:57:21

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

此外,您可能希望将目录列表读取到一个数组中,关闭该目录,然后在该数组上递归。这可能有助于遍历非常深的目录结构。

票数 4
EN

Stack Overflow用户

发布于 2012-04-29 11:05:47

文件cat /proc/sys/fs/

-nr

它提供了什么?

输出格式为:(已分配的文件处理程序数)-(已分配但未使用的文件处理程序数)-(最大文件处理程序数)

如果你得到了更多数量的已分配但未使用的文件处理程序,这意味着你必须关闭@Matthew Iselin提到的目录。

您还可以更改系统限制。

有关更改系统限制Can be found here的更多信息。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10369309

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档