美文网首页
fopen_s、fscanf_s、fprintf_s、fclos

fopen_s、fscanf_s、fprintf_s、fclos

作者: Kylin824 | 来源:发表于2018-04-15 14:57 被阅读0次
#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 );  
   }  
}

相关文章

网友评论

      本文标题:fopen_s、fscanf_s、fprintf_s、fclos

      本文链接:https://www.haomeiwen.com/subject/qcbdkftx.html