对于这两个函数,fopen是较老版本的函数,fopen_s在老版本上加入了溢出安全检测。
高版本的VS中使用fopen函数,经常会出现这样的警告:
warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use_CRT_SECURE_NO_WARNINGS. See online help for details.
在Windows应用编程中,提倡使用新版本的函数以保证代码的安全性,提议大家使用fopen_s这个函数。对于一些较老的程序,不方便修改时,也可以在项目->属性->C/C++->预处理器->预处理器定义中加入_CRT_SECURE_NO_WARNINGS来使用这些老版本的函数。
两个函数的原型:
_ACRTIMP FILE* __cdecl fopen(
_In_z_ char const* _FileName,
_In_z_ char const* _Mode
);
fopen函数有两个实参:_FileName文件名和文件打开模式,
返回值:文件打开成功,将返回一个指向该文件的指针,打开错误时,将返回一个空指针NULL,在大多数库实现中,系统特定的错误代码将写入到error变量中。
实例:FILE* pFile;
if((pFile = fopen("文件名","mode"))==NULL)
return 0; // 打开失败
else
return 1; //打开成功
_ACRTIMP errno_t __cdecl fopen_s(
_Outptr_result_maybenull_ FILE** _Stream,
_In_z_ char const* _FileName,
_In_z_ char const* _Mode
);
fopen_s函数有三个实参:_FileName文件名和文件打开模式同上,第一个参数_Stream是一个指向该文件指针的指针,
返回值:errno_t类型的一个变量,用来存储错误代码,文件打开成功,函数返回0,失败则返回相应的错误代码,为非0。
下面给出两个通用的示例:
一、fopen函数:
/* fopen example */
#include <stdio.h>
int main()
{
FILE * pFile;
pFile = fopen("myfile.txt", "w");
if (pFile != NULL)
{
fputs("fopen example", pFile);
fclose(pFile);
}
return 0;
}
二、fopen_s函数:
/* fopen_s example */
#include <stdio.h>
FILE* stream, *stream2;
int main()
{
int numclosed;
errno_t err;
// Open for read
if ((err = fopen_s(&stream, "crt_fopen_s.c", "r")) != 0)
printf("The file 'crt_fopen_s.c was not opened\n");
else
printf("The file 'crt_fopen_s.c was opened\n");
// Open for write
if ((err = fopen_s(&stream2, "data2", "w+")) != 0)
printf("The file 'data2' was not opened.\n");
else
printf("The file 'data2' was opened.\n");
// Close stream if ti is not NULL
if (stream)
{
if (fclose(stream))
printf("The file 'crt_fopen_s.c was not closed.\n");
}
// All other files are closed
numclosed = _fcloseall();
printf("Number of files closed by _fcloseall;%u\n", numclosed);
return 0;
}
注:fopen_s函数还有一个宽字节的版本,即支持UINCODE文件流的版本
errno_t _wfopen_s(
FILE** pFile,
const wchar_t *filename,
const wchar_t *mode
);
与fopen_s函数用法相同,不再赘述。
浙公网安备 33010602011771号