在利用fprintf函数将数据按格式输出到文件中时,通常需要限定数据的格式,例如:
FILE *f=fopen("d:\1.txt","w+"); int a =20; float b = 3.006544; double c = 6.2154857; fprintf(f,"%6d%c",a,','); fprintf(f,"%2.6f%c",b,','); fprintf(f,"%2.6lf%c",b,' ');
fclose(f);
但是在利用fscanf等函数进行文件读取时,并不需要再加这些数字限定,直接读取即可。对应float和double类型的数据,如果仍加数字限定,进行读取时会无法正确读取数据;但是对于int型数据,即便加上这些数字限定(实际上完全没有必要加),仍然会得到准确数据。
FILE *f=fopen("d:\1.txt","r");
int a =0;
float b = 0;
double c = 0;
char temp;
fscanf(f,"%6d",&a);//可以得到准确数据
fscanf(f,"%c",&temp);
fscanf(f,"%2.6f",&b');//读取数据错误
fscanf(f,"%c",&temp);
fscanf(f,"%2.6lf",&b,);//读取数据出错
fscanf(f,"%c",&temp);
fclose(f);
因此,推荐的数据读取的方式为:
FILE *f=fopen("d:\1.txt","r"); int a =0; float b = 0; double c = 0; char temp; fscanf(f,"%d",&a);//可以得到准确数据 fscanf(f,"%c",&temp); fscanf(f,"%f",&b');//可以得到准确数据 fscanf(f,"%c",&temp); fscanf(f,"%lf",&b,);//可以得到准确数据 fscanf(f,"%c",&temp); fclose(f);