Reputation: 1898
I was doing some simple read/write operations on files using MS Visual Studio. Here is a simplified version of the code I wrote:
#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);
}
Whenever I run the program, it gets stuck and does not end. I debugged the code and traced into it. Turned out that all parts of the code are okay and run without any problems, except the line that contains fclose
. I mean, the debugger gets stuck when it reaches that line. Why this happens and what is the problem?
EDIT :
I suspected that the problem is with the name of files, specially com4.ini
. So I changed the code as follows:
#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);
}
The funny thing is, it writes the first file successfully. For the second file, it passes the existence check and again, gets stuck at the last line. It doesn't even throw an exception! Just remains there doing nothing...
Upvotes: 0
Views: 289
Reputation: 30035
You can't use COM4.ini as a filename, see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx Specifially
"CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9. Also avoid these names followed immediately by an extension; for example, NUL.txt is not recommended. For more information, see Namespaces."
It attempts to open a serial port called COM4 instead...
Upvotes: 4