我编写这段代码来打印 /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/