windows中的fopen_s,fprintf_s,fscanf_s等安全增强操作函数

一 、安全增强函数   

  VS中进行编程时,经常会遇到 使用fopen不安全,建议使用fopen_s替代的警告:

    

    因为 CRT(C运行时库)中的很多函数并不进行参数的越界检测。因此windows提供了对于这些函数的安全增强版本。就是对旧版本加后缀_s ("secure") 。其中有对于文件操作的有fopen_s,fprintf_s,fscanf_s等。还有sprintf_s,strcat_s,strcpy_s等。

    这些安全增强函数并没有避免错误。只是在原来的基础上增加了安全检测。在越界时,返回错误码(设置errno值)。

 二、 fopen 与fopen_s对比

(1) 函数原型

errno_t fopen_s( 
   FILE** pFile,
   const char *filename,
   const char *mode 
);
FILE *fopen( 
   const char* filename, 
   const char* mode 
);
(2)返回值

fopen成功调用是返回文件指针;失败时返回NULL

fopen_s成功是返回0;失败时返回错误码

pFile

filename

mode

Return Value

Contents ofpFile

NULL

any

any

EINVAL

unchanged

any

NULL

any

EINVAL

unchanged

any

any

NULL

EINVAL

unchanged

(3)说明

使用fopen_s打开的文件时不可以共享的。
(4)示例

// This program opens two files. It uses
// fclose to close the first file and
// _fcloseall to close all remaining files.
 

#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 );
}
执行结果:

The file 'crt_fopen_s.c' was opened
The file 'data2' was opened
Number of files closed by _fcloseall: 1



猜你喜欢

转载自blog.csdn.net/zxx910509/article/details/56479490