操作系统:ubuntu
#include <stdio.h>
int main()
{
FILE *fp;
float write=23.1054;
float read=0;
fp=fopen("location.bat","w+");
fwrite(&write,sizeof(float),1,fp);
fread(&read,sizeof(float),1,fp);
fprintf(stderr,"read is :%f \n",read);
//fread(&read,sizeof(float),1,fp);
//fprintf(stderr,"read second is:%f \n",read);
fclose(fp);
return 0;
}
使用以上程序进行浮点数的写入读出操作时,发现输出结果是:
read is :0.000000
原因是fwrite之后必须关闭文件,重新打开之后才能使用fread,相当于你得先保存文件才能正确读取内容。
fwrite在对文件进行写入操作时,并不会直接写入磁盘,而是写入到内核缓冲区中,内核会在适当的时候将数据写入到磁盘中
修改成下面这样就可以了:
#include <stdio.h>
int main()
{
FILE *fp;
float write=23.1054;
float read=0;
fp=fopen("location.bat","w+");
fwrite(&write,sizeof(float),1,fp);
fclose(fp);
fp=fopen("location.bat","r+");
fread(&read,sizeof(float),1,fp);
fprintf(stderr,"read is :%f \n",read);
fclose(fp);
return 0;
}
原文http://hi.baidu.com/jackenne/item/3c86a309be4b9e863c42e283