我在我们内部的一个 dll 中遇到了以下代码,我试图了解它所显示的行为:
long GetFD(long* fd, const char* fileName, const char* mode)
{
string fileMode;
if (strlen(mode) == 0 || tolower(mode[0]) == 'w' || tolower(mode[0]) == 'o')
fileMode = string("w");
else if (tolower(mode[0]) == 'a')
fileMode = string("a");
else if (tolower(mode[0]) == 'r')
fileMode = string("r");
else
return -1;
FILE* ofp;
ofp = fopen(fileName, fileMode.c_str());
if (! ofp)
return -1;
*fd = (long)_fileno(ofp);
if (*fd < 0)
return -1;
return 0;
}
long CloseFD(long fd)
{
close((int)fd);
return 0;
}
在使用适当的 CloseFD 重复调用 GetFD 之后,整个 dll 将不再能够执行任何文件 IO。我写了一个测试程序,发现我可以GetFD 509次,但是第510次会出错。
使用 Process Explorer,句柄数没有增加。
看来dll 已达到打开文件数的限制;设置 _setmaxstdio(2048)
确实会增加我们调用 GetFD 的次数。显然,close() 工作正常。
经过一些搜索,我将 fopen()
调用替换为:
long GetFD(long* fd, const char* fileName, const char* mode)
{
*fd = (long)open(fileName, 2);
if (*fd < 0)
return -1;
return 0;
}
现在,重复调用 GetFD/CloseFD 就可以了。
这是怎么回事?
最佳答案
如果您使用fopen
打开一个文件,您必须对称地使用fclose
关闭它。
C++ 运行时必须有机会清理/释放其内部文件相关结构。
关于c++ - 为什么在 fopen() 没有关闭之后调用 close()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2592449/