Home:ALL Converter>How to use feof to read an undefined number of float values from a binary file?

How to use feof to read an undefined number of float values from a binary file?

Ask Time:2021-10-27T20:17:44         Author:alma korte

Json Formatter

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?

Author:alma korte,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69738539/how-to-use-feof-to-read-an-undefined-number-of-float-values-from-a-binary-file
yy