c++中fopen和fopen_s比较

c++中fopen和fopen_s比较

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

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

errno_t fopen_s( FILE** pFile, const char *filename, const char *mode );

pFile:文件指针将接收到打开的文件指针指向的指针。filename:文件名。mode:访问类型。
返回值:如果成功返回0,失败则返回相应的错误代码。

建议用fopen_s,比fopen多了溢出检测,更安全一些。
#include <stdio.h>

FILE *stream, *stream2;

int main( void )
{
   int numclosed;
   errno_t err;

   // Open for read (will fail if file "crt_fopen_s.c" does not exist)
   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 it 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 );
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值