该函数需要头文件:#include<stdio.h>
在vs编程中,经常会有这样的警告: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. 是因为 fopen_s比fopen多了溢出检测,更安全一些。(在以后的文章里还有get与get_s的比较,strcpy strcpy_s的比较,他们的共同点都是用来一些不可预料的行为,以后将进行详尽解释)
在定义FILE * fp 之后,fopen的用法是: fp = fopen(filename,"w")。而对于fopen_s来说,还得定义另外一个变量errno_t err,然后err = fopen_s(&fp,filename,"w")。返回值的话,对于fopen来说,打开文件成功的话返回文件指针(赋值给fp),打开失败则返回NULL值;对于fopen_s来说,打开文件成功返回0,失败返回非0。
fopen 和 fopen_s用法上的区别:
fopen_s 函数原型
fopen_s,_wfopen_s 打开一个文件,这些版本比fopen,_wfopen在安全性上都有增强。 使用方法: --------------------------------------------------- errno_t fopen_s( FILE** pFile, const char *filename, const char *mode ); errno_t _wfopen_s( FILE** pFile, const wchar_t *filename, const wchar_t *mode );
函数参数和返回值
[输出] pFile
文件访问方式
"r"当使用”a”和”a+”来打开一个文件时,光标会自动移动到EOF处,如果需要定位光标,则需要用到fseek 或者 rewind 函数。
CFileDialog dlg(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,"(*.txt)|*.txt||");
if (dlg.DoModal() != IDOK)
{
return;
}
CString strPath = dlg.GetPathName();
FILE* fp;
if ( 0!=fopen_s(&fp,strPath,"r+"))
{
MessageBox("Open file failed!");
}
char ch;
ch = fgetc(fp);
m_OpenTXT+=ch;
while (ch != EOF)
{
ch = fgetc(fp);
m_OpenTXT+=ch;
}
UpdateData(FALSE);
fclose(fp);
本文详细介绍了fopen和fopen_s两个函数在文件操作中的不同之处,包括它们的安全特性、使用方法及返回值的区别,并提供了示例代码。
1062





