fopen和fopen_s用法的比較

open和fopen_s用法的比較  

fopen 和 fopen_shtml

 

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

        fopen_s用法:,須定義另一個變量errno_t err,而後err = fopen_s(&fp,filename,"w")。安全

       返回值: fopen打開文件成功,返回文件指針(賦值給fp),打開失敗則返回NULL值;ide

                      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的比較,他們的共同點都是用來一些不可預料的行爲,之後將進行詳盡解釋)orm

#includehtm

FILE *stream, *stream2;blog

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

 
來自: https://www.cnblogs.com/1996313xjf/p/6012228.html 
相關文章
相關標籤/搜索