std::fclose()有一个非常奇怪的问题

A very odd issue with std::fclose()

本文关键字:问题 非常 有一个 fclose std      更新时间:2023-10-16

我正在使用MS Visual Studio对文件进行一些简单的读/写操作。下面是我写的代码的简化版本:

#include <cstdio>
#include <cstring>
void write_into_file(const char* filename);
int main()
{
    write_into_file("settings.ini");
    write_into_file("com4.ini");
    return 0;
}
void write_into_file(const char* filename)
{
    FILE* f = std::fopen(filename, "wb");
    const char* text = "Some text I want to write...";
    std::fwrite(text, 1, strlen(text), f);
    std::fclose(f);
}

每当我运行程序时,它就卡住了,而且不结束。我调试了代码并进行了追踪。结果,代码的所有部分都可以正常运行,没有任何问题,除了包含fclose的那行。我的意思是,当它到达那一行时,调试器就卡住了。为什么会发生这种情况,问题是什么?

编辑:

我怀疑是文件名的问题,特别是com4.ini。所以我将代码修改如下:

#include <fstream>
#include <sys/stat.h>
void write_into_file(const char* filename)
{
    std::ofstream fp(filename, std::ios::out);
    if (fp.is_open())
        fp.close();
    struct stat info;
    if (stat(filename, &info) != 0)
    {
        perror("An error occurred. Write permissions maybe?!!");
        return;
    }
    FILE* f = std::fopen(filename, "wb");
    const char* text = "Some text I want to write...";
    std::fwrite(text, 1, strlen(text), f);
    std::fclose(f);
}
有趣的是,它成功地写了第一个文件。对于第二个文件,它通过了存在性检查,并再次卡在最后一行。它甚至不会抛出异常!只是呆在那里什么也不做…

不能使用COM4.ini作为文件名,参见https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspxSpecifially

"CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9。也要避免这些名字后面紧跟着一个扩展名;例如,不建议使用"null .txt"。有关更多信息,请参见名称空间。"

它试图打开一个名为COM4的串行端口…