首页 > 代码库 > fopen和fopen_s用法的比较

fopen和fopen_s用法的比较

fopen和fopen_s用法的比较  

fopen 和 fopen_s

 

        fopen用法: fp = fopen(filename,"w")。

        fopen_s用法:,须定义另外一个变量errno_t err,然后err = fopen_s(&fp,filename,"w")。

       返回值: fopen打开文件成功,返回文件指针(赋值给fp),打开失败则返回NULL值;

                      fopen_s打开文件成功返回0,失败返回非0。

 

在定义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多了溢出检测,更安全一些。(在以后的文章里还有get与get_s的比较,strcpy strcpy_s的比较,他们的共同点都是用来一些不可预料的行为,以后将进行详尽解释)

#include

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

 

fscanffscanf_s用法的比较 

 

fscanf 和 fscanf_s

 

      fscanf用法:fscanf(fp,"%d",&var)

      fscanf_s用法:fscanf(fp,"%d",&var,sizeof(int))

      区别:fscanf_s需要指定长度

 

fscanf(格式化字符串输入)
相关函数
scanf,sscanf
表头文件
#include<stdio.h>
定义函数
int fscanf(FILE * stream ,const char *format,....);
函数说明
fscanf()会自参数stream的文件流中读取字符串,再根据参数format字符串来转换并格式化数据。格式转换形式请参考scanf()。转换后的结构存于对应的参数内。
返回值
成功则返回参数数目,失败则返回-1,错误原因存于errno中。
附加说明
 
范例
#include<stdio.h>
main()
{
int i;
unsigned int j;
char s[5];
fscanf(stdin,”%d %x %5[a-z] %*s %f”,&i,&j,s,s);
printf(“%d %d %s \n”,i,j,s);
}
执行
10 0x1b aaaaaaaaa bbbbbbbbbb
10 27 aaaaa

 fscanf函数:

fscanf(fp,"%s",temp_str);和fscanf(fp,"%lf",&min_snr);

fscanf就是从文件中读取数据,保存到第三个参数开始的变量里,fp是一个FILE类型的指针。fscanf(fp,"%s",temp_str);  // 就是从文件指针fp里面读取一个字符串,保存到temp_str里面,跟scanf差不多,只是scanf是从键盘输入,fscanf是从文件里读取fscanf(fp,"%lf",&min_snr); 

fopen和fopen_s用法的比较