随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)
在控制台操作时,使用的格式化输入和输出为scanf和printf,那么对文件的IO操作也可以使用fscanf和fprintf,它们的使用如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const int LENGTH=80;
int main(void){
long num1=234567L;
long num2=345123L;
long num3=789234L;
long num4=0L;
long num5=0L;
long num6=0L;
float fnum=0.0f;
int ival[6]={0};
FILE *pfile=NULL;
char * filename="C:\\temp\\test.txt";
pfile=fopen(filename,"w");
if(pfile==NULL)
{
printf("Fail to open\n");
exit(1);
}
fprintf(pfile,"%61d%61d%61d",num1,num2,num3);
fclose(pfile);
printf("\n %61d %61d %61d",num1,num2,num3);
pfile=fopen(filename,"r");
fscanf(pfile,"%2d%3d%3d%3d%2d%2d%3f",&ival[0],&ival[1],&ival[2],&ival[3],&ival[4],&ival[5],&fnum);
fclose(pfile);
remove(filename);
printf("\n");
for (int i=0;i<6;i++)
printf("%s ival[i]=%d",i==4?"\n\t":"\t",i,ival[i]);
printf("\nfnum=%f\n",fnum);
return 0;
}