2025年4月7日 星期一 乙巳(蛇)年 正月初八 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > C语言

C语言fscanf()函数:将文件流中的数据格式化输入

时间:12-29来源:作者:点击数:107

头文件:#include <stdio.h>

fscanf() 函数用于将文件流中的数据格式化输入,其原型为:
    int fscanf(FILE * stream, char *format [, argument ,... ] );

【参数】stream为文件指针,format为格式化字符串,argument 为格式化控制符对应的参数。

关于参数和返回值的更多信息请参考 scanf() 函数,这里不再赘述。

fscanf( stdin, format [, argument ,... ] ) 等价于 scanf( format [, argument ,... ] ),fscanf() 可以指定读取的流,scanf() 只能从标准输入流(stdin)读取。

【实例】往文件中写入一组格式化的数据,然后以格式化方式读取并显示。

  • #include<iostream.h>
  • #include<stdio.h>
  • FILE* stream;
  • void main(void)
  • {
  • long l;
  • float fp;
  • char s[81];
  • char c;
  • stream = fopen("fscanf.txt","w+");
  • if(stream == NULL)
  • {
  • printf("the file is opeaned error!\n");
  • }
  • else
  • {
  • fprintf(stream,"%s %ld %f %c","a_string",6500,3.1415,'x');
  • fseek(stream,0L,SEEK_SET); /*定位文件*/
  • fscanf(stream,"%s",s); /*格式化*/
  • fscanf(stream,"%ld",&l);
  • fscanf(stream,"%f",&fp);
  • fscanf(stream," %c",&c);
  • printf("%s\n",s);
  • printf("%ld\n",l);
  • printf("%f\n",fp);
  • printf("%c\n",c);
  • fclose(stream); /*关闭*/
  • }
  • }

运行结果:

a_string
6500
3.141500

程序先创建一个新文件fscanf.txt,如果创建成功则使用 fprintf() 函数输入4个格式数据,然后定位文件到文件的开头,再使用 fscanf() 函数逐个读取出来并显示。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门