【发布时间】:2011-08-02 05:46:49
【问题描述】:
我有以下代码,它只是将一些文本和一个变量打印到文件中。我收到错误“打开的文件太多”。我在 VS2010 的 Windows 上使用 C。
int i, count = 0;
FILE *f;
int _x, _y, _z, _x2, _y2, _z2;
for (i = 0; i < HEIGHT * WIDTH*3; i+= 3)
{
if (buffer1[i/3] < MAGIC_VALUE)
{
count++;
}
if (buffer2[i/3] < MAGIC_VALUE)
{
count++;
}
}
printf("Count = %d\n", count); // prints correctly...
f = fopen("file.abc", "w"); // f == NULL. perror gives "Too many open files"
fprintf(f, "lots\n of\n text\n");
fprintf(f, "count: %d\ntext \ntext y\ntext text text", count);
fprintf(f, "\nend");
fclose(f);
当它运行时,除了 Visual Studio 之外,我没有打开任何东西。
【问题讨论】:
-
这段代码只是炸弹,它永远不能给你这样的诊断。贴出真实代码。
-
什么?这是真实的代码。唯一缺少的是,在 f = fopen("file.abc", "w"); 之后,有 "if (f == NULL) { perror("Error:");}
-
?这是当前写入文件的全部过程。
-
您发布的代码不可能在整个源代码附近。至少,没有对
的引用,并且您还没有定义 buffer1 或 buffer2。发布可以(a)实际编译的最小程序; (b) 证明问题。 Hans Passant 说得对:发布真实代码。 -
我预测问题在于 fopen 在某些循环结构中被重复调用。要么调用 fclose,要么使用逻辑避免重复调用 fopen。