[英]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.