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的返回值是相应的错误代码,有助于排查问题
   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' );  
      // 设置文件指针指向文件头
      fseek( stream, 0L, SEEK_SET );  

      // 读出
      fscanf_s( stream, "%s", s, _countof(s) );  // 读字符串,要加上字符串长度参数
      fscanf_s( stream, "%ld", &l );  // 读整数

      fscanf_s( stream, "%f", &fp );  // 读浮点数
      fscanf_s( stream, "%c", &c, 1 );  //读单个字符,注意要加上参数1

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

      // 释放文件资源,关闭文件
      fclose( stream );  
   }  
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容