fopen被弃用警告

74

使用 Visual Studio 2005 C++ 编译器 编译代码中使用 fopen() 等函数时,我会收到以下警告:

1>foo.cpp(5) : warning C4996: 'fopen' was declared deprecated
1>        c:\program files\microsoft visual studio 8\vc\include\stdio.h(234) : see declaration of 'fopen'
1>        Message: 'This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See online help for details.'

我该如何防止这种情况发生?

11个回答

0
为了改进上面的答案,对我有用的是拥有这个宏。
#include "stdio.h"
#if (defined(_MSC_VER) && (_MSC_VER >= 1400) )

static inline
FILE* fn_fopen(const char* fname, const char* mode)
{
    FILE* fptr;
    errno_t err = fopen_s(&fptr, fname, mode);
    if (err != 0) {
        return NULL;
    }
    return fptr;
}
#define _fopen_(fname, mode)   fn_fopen((fname), (mode))

#else

#define _fopen_(fname, mode)   fopen((fname), (mode))

#endif 

然后,您可以打开文件

FILE* fp = _fopen_(filename, "rb");
if (fp == NULL) {
/* Cannot open the file */
}

我不喜欢重新定义fopen(),而是使用自己的宏。这样可以避免一些潜在的问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接