Share via


How use 'fopen_s' for open file?

Question

Sunday, July 17, 2016 2:13 PM

I saw this example to open file:

int main(){FILE * pFile;
pFile = fopen("myfile.txt", "w");

    if (pFile != NULL)
    {
        fputs("fopen example", pFile);
        fclose(pFile);
    }
return 0;}

But when I run this code was a error:

Error C4996 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

So I used  'fopen_s' and ran this code:

int main(){FILE * pFile;
FILE * stream;
pFile = fopen_s(&stream,"myfile.txt", "w");
    if (pFile != NULL)
    {
        fputs("fopen example", pFile);
        fclose(pFile);
    }return 0;}

 But was a this error:

Error C2440 '=': cannot convert from 'errno_t' to 'FILE *'

What I need to do for corect compile this code?

All replies (5)

Sunday, July 17, 2016 2:21 PM ✅Answered | 1 vote

The fopen_s function return type is errno_t and you're trying to assign it to a variable of type FILE *, which is what the compiler is telling you.

Have a look at the example on the fopen_s function documentation page to see how to use it correctly.

Cheers
Eddie


Sunday, July 17, 2016 2:25 PM ✅Answered | 1 vote

> What I need to do for corect compile this code?

1. Read the documentation for fopen_s.

2. Curse (or thank Microsoft for easy and intuitive API if you like)

3. Fix your code

-- pa


Sunday, July 17, 2016 7:27 PM

Hi

#include <stdlib.h>

error_t pFile;

FILE * stream;

pFile = fopen_s(&stream,"myfile.txt", "w");

if (pFile == NULL) { fputs("fopen example", stream); fclose(stream); }

Regards

Chong


Sunday, July 17, 2016 7:30 PM

Hi

#include <stdlib.h>

error_t pFile;

FILE * stream;

pFile = fopen_s(&stream,"myfile.txt", "w");

if (pFile == NULL) { fputs("fopen example", stream); fclose(stream); }

Regards

Chong

No, not again. Not here. Please.

-- pa


Sunday, July 17, 2016 7:49 PM

Ok Pavel

My apology!

Regards

Chong