简体   繁体   English

如何使用 feof 从二进制文件中读取未定义数量的浮点值?

[英]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.我将一些浮点值写入二进制文件,然后我想用另一个.c程序读回它们。

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.但是我得到了 7.7,这意味着读者从未找到任何值。

How can I do this?我怎样才能做到这一点? What did I miss here?我在这里错过了什么?

In your second program, FILE *fh = fopen ("file.bin", "wb");在你的第二个程序中, 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");将其更改为FILE *fh = fopen ("file.bin", "rb"); and remove the later fh = fopen ("file.bin", "rb");并删除后面的fh = fopen ("file.bin", "rb"); . .

Additionally, do not use feof for testing whether there is more data in a file.此外,不要使用feof来测试文件中是否有更多数据。 feof only reports if EOF or an error occurred on a previous read or write operation. feof仅报告前一次读或写操作是否发生 EOF 或错误。 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.相反,检查fread的返回值以查看它读取了多少项。

If you use size_t result = fread(&x, 1, sizeof (x), fh);如果使用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. ,你要求fread读取sizeof (x)个字节,它会返回读取的字节数。 If that is less than sizeof (x) , then a complete x was not read.如果它小于sizeof (x) ,则未读取完整的x In contrast, if you use size_t result = fread(&x, sizeof x, 1, fh);相反,如果使用size_t result = fread(&x, sizeof x, 1, fh); , you ask fread to read 1 object of size sizeof x . ,您要求fread读取大小为sizeof x 1 个对象。 Then fread will return the number of complete objects read, which will be 0 or 1.然后fread将返回读取的完整对象的数量,该数量将为 0 或 1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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