fopen和fopen_s用法的比较

2023-11-02

在定义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。

在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多了溢出检测,更安全一些。


#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 );
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

fopen和fopen_s用法的比较 的相关文章

  • Ant Design 常见用法与坑点总结(一)

    前言 Ant Design 是蚂蚁出品的出色优秀的 React 组件库 相信使用 React 进行管理系统开发的小伙伴们或多或少都接触过 Ant Design 很多公司基于 React 开发的管理端系统也都是使用 Ant Design 的组
  • 运动估计与运动补偿

    运动估计与运动补 偿 改正 2010 11 17 10 29 29 运动补偿是通过先前的局部图像来预测 补偿当前的局部图像 它是减少帧序列冗余信息的有效方法 运动估计是从视频序列中抽取运动信息的一整套技术 运动估计与运动补偿技术 MPEG

随机推荐