[英]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,這意味着讀者從未找到任何值。
我怎樣才能做到這一點? 我在這里錯過了什么?
在你的第二個程序中, FILE *fh = fopen ("file.bin", "wb");
打開文件進行寫入並將其截斷為零長度,從而破壞其中的數據。 將其更改為FILE *fh = fopen ("file.bin", "rb");
並刪除后面的fh = fopen ("file.bin", "rb");
.
此外,不要使用feof
來測試文件中是否有更多數據。 feof
僅報告前一次讀或寫操作是否發生 EOF 或錯誤。 如果沒有嘗試讀取過去,它不會告訴您文件位置指示器當前指向文件末尾。 相反,檢查fread
的返回值以查看它讀取了多少項。
如果使用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
1 個對象。 然后fread
將返回讀取的完整對象的數量,該數量將為 0 或 1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.