【发布时间】:2011-08-24 12:52:15
【问题描述】:
我正在循环中使用以下代码将大约 6000 个文本文件读入内存:
void readDocs(const char *dir, char **array){
DIR *dp = opendir(dir);;
struct dirent *ep;
struct stat st;
static uint count = 0;
if (dp != NULL){
while (ep = readdir(dp)){ // crawl through directory
char name[strlen(dir) + strlen(ep->d_name) + 2];
sprintf(name, "%s/%s", dir, ep->d_name);
if(ep->d_type == DT_REG){ // regular file
stat(name, &st);
array[count] = (char*) malloc(st.st_size);
int f;
if((f = open(name, O_RDONLY)) < 0) perror("open: ");
read(f, array[count], st.st_size));
if(close(f) < 0) perror("close: ");
++count;
}
else if(ep->d_type == DT_DIR && strcmp(ep->d_name, "..") && strcmp(ep->d_name, "."))
// go recursive through sub directories
readDocs(name, array);
}
}
}
在第 2826 次迭代中,我在打开第 2826 个文件时收到“打开的文件太多”错误。
至此,关闭操作没有发生错误。
由于它总是在第 2826 次迭代中挂起,我不认为我应该等到调用 close();
后文件真正关闭
我在使用 fopen、fread 和 fclose 时遇到了同样的问题。
我不认为它与这个 sn-p 的上下文有关,但如果你这样做,我会提供它。
感谢您的宝贵时间!
编辑:
我让程序进入睡眠状态并检查了 /proc//fd/ (感谢 nos)。就像您怀疑的那样,我发现正好有 1024 个文件描述符,这是一个通常的限制。
+ 我为您提供了从目录和所有子目录中读取文档的整个功能
+ 程序在 Linux 上运行!很抱歉忘记了!
【问题讨论】:
-
某处,您没有关闭()文件,可能在错误路径上。如果这是在 linux 上,请查看 /proc/
/fd/ ,您至少会看到哪些文件描述符无法关闭() -
好像系统在调用 close() 后实际上正在关闭文件。你在哪个系统下运行这个程序?
-
我们确实需要更多代码和详细信息。
-
@nos 我发现确实有几个文件处于打开状态。问题是为什么。