两者都是打开文件用的函数,其中fopen_s是c++11之后增加的安全增强版本,增加了安全检测。

fopen

打开由该文件指示的文件filename并返回指向与该文件关联的文件流的指针。mode用于确定文件访问模式。

函数形式:FILE * fopen (const char * filename, const char * mode);

用法:fp = fopen(filename, "w");
如果打开文件成功,返回文件指针,打开失败则返回NULL。

mode:

访问模式字符串 说明
“r” read:打开文件进行输入操作。该文件必须存在。
“w” write:为输出操作创建一个空文件。如果已存在具有相同名称的文件,则会丢弃其内容,并将该文件视为新的空文件。
“a” append:打开输出文件的末尾。输出操作总是在文件末尾写入数据。重定位操作(fseek,fsetpos,rewind)将被忽略。如果文件不存在,则创建该文件。
“r+” read/update:打开文件进行更新(包括输入和输出)。该文件必须存在。
“w+” write/update:创建一个空文件并打开它进行更新(包括输入和输出)。如果已存在具有相同名称的文件,则会丢弃其内容,并将该文件视为新的空文件。
“a+” append/update:打开一个文件进行更新(包括输入和输出),所有输出操作都在文件末尾写入数据。重定位操作(fseek,fsetpos,rewind)会影响下一个输入操作,但输出操作会将位置移回文件末尾。如果文件不存在,则创建该文件。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
/* 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不同的是需要另外定义一个变量errno_t err,用来表示文件是否打开成功。若打开成功返回0,失败返回非0,。

函数形式:errno_t fopen_s(FILE ** pFile,const char *filename,const char* mode;

用法:err = fopen_s(&fp, filename, "w");
mode与fopen相同。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* fopen_s example */
#include <stdio.h>
int main ()
{
FILE * fp;
err = fopen_s (&fp, "myfile.txt","w");
if (err == 0)
{
printf("The file was opened\n.");
fclose (fp);
}
else
{
printf("The file was not opened.\n");
}
return 0;
}