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

前端 未结 6 895
遇见更好的自我
遇见更好的自我 2020-12-05 10:54

MSVC compiler says that fopen() is deprecated, and recommends the use of fopen_s().

Is there any way to use fopen_s() and stil

6条回答
  •  时光取名叫无心
    2020-12-05 11:26

    Many of Microsoft's secure functions are included in Annex K of the C11 standard, but it is not widely supported, so portability is still an issue. There is a need for the improved security in some applications; maybe the support will improve in the future.

    I the past, I did it like this:

      #define fopen_s(fp, fmt, mode)          *(fp)=fopen( (fmt), (mode))
    

    The macro is simple and straight forward, good enough for something quick and dirty, but it doesn't provide the exception behavior of fopen_s, and it won't provide the security of the real fopen_s function.

    @Alex B's function approach above partially reproduces the proper behavior on failure; he returns errno (= EINVAL). His approach could be extended further by generating an invalid parameter exception to more fully reproduce the behavior of fopen_s.

提交回复
热议问题