std::fclose()有一个非常奇怪的问题
A very odd issue with std::fclose()
我正在使用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的串行端口…
相关文章:
- 对于非常大的输入,缺少和重复 1..n 的数字数组.使用1..n系列特性的解决方案.溢出问题
- 非常基本的MurmurHash问题:len的变量描述,C++实现的关键
- C / C++链接问题与非常简单的设置
- 在 cplex c++ 音乐会 api++ 中处理非常大的问题而不会耗尽内存
- 我在内存泄漏和字符串方面遇到了一个非常奇怪的问题
- 在C++中使用限制和非常大的数字时出现问题
- 绘制非常大的 2D 图形时出现问题
- (c++)代码中一个非常奇怪的问题
- 非常基本的C++问题(预期表达式)
- 回文程序中非常奇怪的问题
- C++和引脚工具 - IF语句非常奇怪的双变量问题
- 非常基本的C++程序问题 - 二进制表达式的操作数无效
- 涉及指针成员变量和多态性的非常奇怪的问题
- 一些人发现此代码存在溢出问题.小的数字是非常负的
- 我在让非常基本的命令提示符文本处理器工作时遇到问题。ofstream() 的问题
- 关于google-nacl的非常简单的问题
- C++中非常大的数组存在内存问题
- c++的问题.我需要帮助一个非常简单和基本的问题在c++
- 关于签名无效*数据的论点的非常基本的问题
- 非常奇怪的GetOpenFileName问题