Is there a way to use fopen_s() with GCC or at least create a #define about it?

if you are using C11, fopen_s is a standard library.

In gcc you need to use --std=c11 parameter.


Microsoft's *_s functions are unportable, I usually use equivalent C89/C99 functions and disable deprecation warnings (#define _CRT_SECURE_NO_DEPRECATE).

If you insist, you can use an adaptor function (not necessarily a macro!) that delegates fopen() on platforms that don't have fopen_s(), but you must be careful to map values of errno_t return code from errno.

errno_t fopen_s(FILE **f, const char *name, const char *mode) {
    errno_t ret = 0;
    assert(f);
    *f = fopen(name, mode);
    /* Can't be sure about 1-to-1 mapping of errno and MS' errno_t */
    if (!*f)
        ret = errno;
    return ret;
}

However, I fail to see how fopen_s() is any more secure than fopen(), so I usually go for portability.


In C/C++ code,

#ifdef __unix
#define fopen_s(pFile,filename,mode) ((*(pFile))=fopen((filename),(mode)))==NULL
#endif

In Makefile

CFLAGS += -D'fopen_s(pFile,filename,mode)=((*(pFile))=fopen((filename),(mode)))==NULL'

Attention that on success fopen_s return 0 while fopen return a nonzero file pointer. Therefore it is necessary to add "==NULL" to the end of macro, e.g.:

if (fopen_s(&pFile,filename,"r")) perror("cannot open file");