Sha*_*tia 14 c gcc fopen visual-c++
MSVC编译器说不fopen()
推荐使用,并建议使用fopen_s()
.
有什么方法可以使用fopen_s()
并且仍然可移植吗?
有#define
什么想法?
Ale*_*x B 28
Microsoft的*_s
函数是不可移植的,我通常使用等效的C89/C99函数并禁用弃用警告(#define _CRT_SECURE_NO_DEPRECATE
).
如果你坚持,你可以使用在没有的fopen()
平台上委托的适配器函数(不一定是宏!)fopen_s()
,但是你必须小心地映射errno_t
返回代码的值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;
}
Run Code Online (Sandbox Code Playgroud)
但是,我没有看到如何fopen_s()
更安全fopen()
,所以我通常会寻求便携性.
如果您使用的是C11,fopen_s
则是标准库:
http://en.cppreference.com/w/c/io/fopen
在gcc
你需要使用--std=C11
参数.
在C/C++代码中,
#ifdef __unix
#define fopen_s(pFile,filename,mode) ((*(pFile))=fopen((filename),(mode)))==NULL
#endif
Run Code Online (Sandbox Code Playgroud)
在Makefile中
CFLAGS += -D'fopen_s(pFile,filename,mode)=((*(pFile))=fopen((filename),(mode)))==NULL'
Run Code Online (Sandbox Code Playgroud)
注意,成功时fopen_s返回0而fopen返回非零文件指针.因此有必要在宏的末尾添加"== NULL",例如:
if (fopen_s(&pFile,filename,"r")) perror("cannot open file");
Run Code Online (Sandbox Code Playgroud)