简体   繁体   中英

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

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?

In your second program, FILE *fh = fopen ("file.bin", "wb"); opens the file for writing and truncates it to zero length, destroying the data in it. Change that to FILE *fh = fopen ("file.bin", "rb"); and remove the later fh = fopen ("file.bin", "rb"); .

Additionally, do not use feof for testing whether there is more data in a file. feof only reports if EOF or an error occurred on a previous read or write operation. It does not tell you that the file position indicator is currently pointing to the end of the file, if no attempt to read past that has been made. Instead, check the return value of fread to see how many items it read.

If you use size_t result = fread(&x, 1, sizeof (x), fh); , you ask fread to read sizeof (x) bytes, and it will return the number of bytes read. If that is less than sizeof (x) , then a complete x was not read. In contrast, if you use size_t result = fread(&x, sizeof x, 1, fh); , you ask fread to read 1 object of size sizeof x . Then fread will return the number of complete objects read, which will be 0 or 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM