c++ - 为什么在 fopen() 没有关闭之后调用 close()?

标签 c++ c file io

我在我们内部的一个 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/

相关文章:

c++ - Oracle 7 ProC++ 预编译代码

c - 二进制 int 到二进制 char

c - 如何更改 CFS 中使用的数据结构

regex - 检索文件名的一部分

java - 如何从客户端的 Controller 下载 zip 文件? Spring Boot

java - java中如何以大写和小写字母存储同名文件

c++ - '.' 之前的预期主表达式

c++ - constexpr 中的字节顺序

C段错误问题

c++ - 如何在 C++ 中绘制多边形以使线条不相交?