fopen和fopen_s的区别

转载:https://blog.csdn.net/keith_bb/article/details/50063075

 

 

fopen:

原型:FILE * fopen(const char * path,const char * mode);接收两个实参

返回值:文件顺利打开后,指向该流的文件指针就会被返回。如果文件打开失败则返回NULL,并把错误代码存在errno 中。

示例程序源码:FILE *cfPtr;

                         if((cfPtr = fopen("test.dat","w")) == NULL)   //若cfPtr = NULL,即文件未成功打开,函数返回0,否则返回1

                                   return 0;

                         else   return 1;

fopen_s:

原型:

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:文件指针将接收到打开的文件指针指向的指针。infilename:文件名。inmode:允许的访问类型。
返回值:如果成功返回0,失败则返回相应的错误代码。

 

 

示例程序源码:(转载自:百度百科)

#include<stdio.h>
 
FILE*stream,*stream2;
 
intmain(void)
 
{
 
errno_terr;
 
//Openforread(willfailiffile"crt_fopen_s.c"doesnotexist)
 
err=fopen_s(&stream,"crt_fopen_s.c","r");
 
if(err==0)
 
{
 
printf("Thefile'crt_fopen_s.c'wasopened\n");
 
}
 
else
 
{
 
printf("Thefile'crt_fopen_s.c'wasnotopened\n");
 
}
 
 
 
//Openforwrite
 
err=fopen_s(&stream2,"data2","w+");
 
if(err==0)
 
{
 
printf("Thefile'data2'wasopened\n");
 
}
 
else
 
{
 
printf("Thefile'data2'wasnotopened\n");
 
}
 
//ClosestreamifitisnotNULL
 
if(stream)
 
{
 
err=fclose(stream);
 
if(err==0)
 
{
 
printf("Thefile'crt_fopen_s.c'wasclosed\n");
 
}
 
else
 
{
 
printf("Thefile'crt_fopen_s.c'wasnotclosed\n");
 
}
 
}
 
//Allotherfilesareclosed:
 
intnumclosed=_fcloseall();
 
printf("Numberoffilesclosedby_fcloseall:%u\n",numclosed);
 
}

 

posted @ 2020-04-08 10:21  梅长苏枫笑  阅读(3205)  评论(0编辑  收藏  举报