fopen_s、fscanf_s、fprintf_s、fclose用法示例

#include <stdio.h>  
#include <stdlib.h>  

FILE *stream;  

int main( void )  
{  
   long l;  
   float fp;  
   char s[81];  
   char c;  

   errno_t err;
   err = fopen_s( &stream, "fscanf.out", "w+" );  
    // fopen的返回值是文件指針,而fopen_s的返回值是相應(yīng)的錯誤代碼,有助于排查問題
   if( err )  
      printf_s( "The file fscanf.out was not opened\n" );  
   else  
   {  
      // 寫入
      fprintf_s( stream, "%s %ld %f%c", "a-string",   
               65000, 3.14159, 'x' );  
      // 設(shè)置文件指針指向文件頭
      fseek( stream, 0L, SEEK_SET );  

      // 讀出
      fscanf_s( stream, "%s", s, _countof(s) );  // 讀字符串,要加上字符串長度參數(shù)
      fscanf_s( stream, "%ld", &l );  // 讀整數(shù)

      fscanf_s( stream, "%f", &fp );  // 讀浮點數(shù)
      fscanf_s( stream, "%c", &c, 1 );  //讀單個字符,注意要加上參數(shù)1

      // Output data read:  
      printf( "%s\n", s );  
      printf( "%ld\n", l );  
      printf( "%f\n", fp );  
      printf( "%c\n", c );  

      // 釋放文件資源,關(guān)閉文件
      fclose( stream );  
   }  
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容