从C中读取二进制文件

时间:2011-11-21 12:13:34

标签: 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 个答案:

答案 0 :(得分:5)

提示:

sizeof(&foo)

不一样:

sizeof(foo)

答案 1 :(得分:3)

你可以一次性编写整个结构,使其更容易阅读:

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

除此之外,您还有错误的sizeof()它不应该是sizeof(&MyRec..) sizeof(MyRec..)没有&