簡體   English   中英

從 C 中的二進制文件讀取

[英]Reading from binary file in C

我有以下結構:

struct Records
{
    int Number;
    char Name[20];
    float Salary;
};

使用以下方法寫入兩條記錄:

fwrite(&MyRecords.Number, sizeof(&MyRecords.Number), 1, binaryfile);
fwrite(&MyRecords.Name, sizeof(&MyRecords.Name), 1, binaryfile);
fwrite(&MyRecords.Salary, sizeof(&MyRecords.Salary), 1, binaryfile);

寫完后,我無法閱讀它。

FILE * read;
read = fopen("binaryfile.dat","rb");

for(int x =0;x<2;x++)
{
fread(&records.Number, sizeof(records.Number), 1, read);
fread(&records.Name, sizeof(records.Name), 1, read);
fread(&records.Salary, sizeof(records.Salary), 1, read);
printf("%d %s %f\n",records.Number,records.Name,records.Salary);
} 

第一行打印兩次,浮點數顯示為一些奇怪的數字。 在過去的 2 個小時里,我已經檢查了兩倍和三倍,但我無法找出我做錯了什么:(

暗示:

sizeof(&foo)

不等同於:

sizeof(foo)

您可以一次性編寫整個結構,使其更易於閱讀:

fwrite(&MyRecords, sizeof(MyRecords), 1, binaryfile);

除此之外,你也有錯誤的sizeof()它不應該是sizeof(&MyRec..)它應該是sizeof(MyRec..)沒有&

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM