提问人:alma korte 提问时间:10/27/2021 最后编辑:chux - Reinstate Monicaalma korte 更新时间:10/27/2021 访问量:67
如何使用 feof 从二进制文件中读取未定义数量的浮点值?
How to use feof to read an undefined number of float values from a binary file?
问:
我将一些浮点值写入二进制文件,然后我想用另一个程序读回它们。.c
我是这样写的:
#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;
}
这就是我想阅读它们的方式:
#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;
}
但是我得到了 7.7,这意味着读者从未找到任何值。
我该怎么做?我在这里错过了什么?
答:
3赞
Eric Postpischil
10/27/2021
#1
在第二个程序中,打开文件进行写入并将其截断为零长度,从而销毁其中的数据。将其更改为并删除后面的 .FILE *fh = fopen ("file.bin", "wb");
FILE *fh = fopen ("file.bin", "rb");
fh = fopen ("file.bin", "rb");
此外,请勿用于测试文件中是否有更多数据。 仅当 EOF 或上一次读取或写入操作发生错误时才报告。它不会告诉您文件位置指示器当前指向文件的末尾,如果没有尝试读取过去。相反,请检查返回值以查看它读取了多少个项目。feof
feof
fread
如果使用 ,则要求读取字节数,它将返回读取的字节数。如果小于 ,则未读取完整。相反,如果使用 ,则要求读取 1 个大小为 的对象。然后将返回读取的完整对象数,即 0 或 1。size_t result = fread(&x, 1, sizeof (x), fh);
fread
sizeof (x)
sizeof (x)
x
size_t result = fread(&x, sizeof x, 1, fh);
fread
sizeof x
fread
评论