I write some float values to a binary file, and after that I want to read them back with another .c
program.
This is how I write them:
#include <stdio.h>
int main() {
/* Create the file */
float x = 1.1;
FILE *fh = fopen ("file.bin", "wb");
if (fh != NULL) {
for (int i = 0; i < 10; ++i)
{
x = 1.1*i;
fwrite (&x,1, sizeof (x), fh);
printf("%f\n", x);
}
fclose (fh);
}
return 0;
}
And this is how I want to read them:
#include <stdio.h>
int main(){
/* Read the file back in */
FILE *fh = fopen ("file.bin", "wb");
float x = 7.7;
fh = fopen ("file.bin", "rb");
if (fh != NULL) {
while(!feof(fh)){
if(feof(fh))
break;
fread (&x, 1, sizeof (x), fh);
printf ("Value is: %f\n", x);
}
fclose (fh);
}
return 0;
}
But I got back 7.7 which means that the reader never found any of the values.
How can I do this? What did I miss here?