How to go from fopen to fopen_s

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.

Leave a Comment