Using fopen_s in C

nikodamn picture nikodamn · Jun 9, 2014 · Viewed 54k times · Source

I have a problem with programming in C, especially with fopen in Visual Studio. I read about the fopen_s function and added the following line to my project, but it still doesn't work.

_CRT_SECURE_NO_WARNINGS

So I tried using fopen_s in this way:

FILE *fp;
errno_t err;
if ((err = fopen_s(&fp, "C:/File.txt", "rt")) != 0)
    printf("File was not opened\n");
else
    fprintf(fp, "Date: %s, Time: %s, Score: %i \n", __DATE__, __TIME__, score);
fclose(fp);

It's still crashing. What's wrong?

Answer

hyde picture hyde · Jun 9, 2014

You use fclose with an invalid fp value, even if opening failed. Add {} around the else branch, at least.

Many developers think it is generally a good idea to use braces everywhere, even with one statement inside them. It's so easy to make a mistake like this if you don't, even for experienced developers. So put them around the then branch too.