头文件:#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); /*关闭*/
- }
- }
运行结果:
程序先创建一个新文件fscanf.txt,如果创建成功则使用 fprintf() 函数输入4个格式数据,然后定位文件到文件的开头,再使用 fscanf() 函数逐个读取出来并显示。