How can I read and write float values to and from a file (using fopen, fwrite etc.)
Ideally each float value would take up 4 bytes on the file, but I'm not sure how to do this. Can anyone help?
Printable View
How can I read and write float values to and from a file (using fopen, fwrite etc.)
Ideally each float value would take up 4 bytes on the file, but I'm not sure how to do this. Can anyone help?
open the files in binary-mode (b-flag).
then use fwrite to write it unformatted to Your file.
Mikey
Code:#include <stdio.h>
int main(){
FILE *fp;
float f=99;
int i;
fp=fopen("test.dat","wb");
for (i=0;i<100;i++){
f++;
fwrite(&f,sizeof(float),1,fp);
}
fclose(fp);
fp=fopen("test.dat","rb");
while (!feof(fp)){
if(fread(&f,sizeof(float),1,fp)>0) printf("%f\n",f);
}
fclose(fp);
return 0;
}