opendir:打开的文件太多了

我写这段代码打印/home/keep with absolution path中的所有文件:

 #include  #include  #include  #include  #include  #include  #include  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 ,然后意识到,我打开了太多文件。

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

当您完成遍历目录的内容时,您应该使用closedir

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

cat / proc / sys / fs / file-nr

它给了什么?
输出格式为:(已分配文件处理程序的数量) – (已分配但未使用的文件处理程序的数量) – (最大文件处理程序数)

如果您获得更多已分配但未使用的文件处理程序,则意味着您必须关闭@Matthew Iselin所述的目录。
您还可以更改系统限制。

有关更改系统限制的更多信息可在此处找到 。