fopen和fopen_s用法的比較


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

 
來自: https://www.cnblogs.com/1996313xjf/p/6012228.html 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM