Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to go from fopen to fopen_s

Visual Studio is complaining about fopen. I can't find the proper syntax for changing it. I have:

FILE *filepoint = (fopen(fileName, "r")); 

to

FILE *filepoint = (fopen_s(&,fileName, "r")); 

What is the rest of the first parameter?

like image 759
beatleman Avatar asked Feb 24 '15 08:02

beatleman


People also ask

What is fopen_s?

The fopen_s function in C is used to securely open files in different modes such as reading and writing. It is secure as it performs robust security checks on the arguments passed to it. For example, it would return an error if the pointer passed to it was NULL .


1 Answers

fopen_s is a "secure" variant of fopen with a few extra options for the mode string and a different method for returning the stream pointer and the error code. It was invented by Microsoft and made its way into the C Standard: it is documented in annex K.3.5.2.2 of the most recent draft of the C11 Standard. Of course it is fully documented in the Microsoft online help. You do not seem to understand the concept of passing a pointer to an output variable in C. In your example, you should pass the address of filepoint as the first argument:

errno_t err = fopen_s(&filepoint, fileName, "r"); 

Here is a complete example:

#include <errno.h> #include <stdio.h> #include <string.h> ... FILE *filepoint; errno_t err;  if ((err = fopen_s(&filepoint, fileName, "r")) != 0) {     // File could not be opened. filepoint was set to NULL     // error code is returned in err.     // error message can be retrieved with strerror(err);     fprintf(stderr, "cannot open file '%s': %s\n",             fileName, strerror(err));     // If your environment insists on using so called secure     // functions, use this instead:     char buf[strerrorlen_s(err) + 1];     strerror_s(buf, sizeof buf, err);     fprintf_s(stderr, "cannot open file '%s': %s\n",               fileName, buf); } else {     // File was opened, filepoint can be used to read the stream. } 

Microsoft's support for C99 is clunky and incomplete. Visual Studio produces warnings for valid code, forcing the use of standard but optional extensions but in this particular case does not seem to support strerrorlen_s. Refer to Missing C11 strerrorlen_s function under MSVC 2017 for more information.

like image 173
chqrlie Avatar answered Sep 19 '22 14:09

chqrlie