Reputation: 2258
I have the following struct:
struct Records
{
int Number;
char Name[20];
float Salary;
};
Writing two records using:
fwrite(&MyRecords.Number, sizeof(&MyRecords.Number), 1, binaryfile);
fwrite(&MyRecords.Name, sizeof(&MyRecords.Name), 1, binaryfile);
fwrite(&MyRecords.Salary, sizeof(&MyRecords.Salary), 1, binaryfile);
After writing, Im having trouble reading from it.
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);
}
The first line gets printed twice, and the float comes out as some weird number. I've double and tripled checked for the past 2 hours yet I cant find out what im doing wrong :(
Upvotes: 0
Views: 228
Reputation: 36082
You could write the whole struct in one go instead, makes it easier to read:
fwrite(&MyRecords, sizeof(MyRecords), 1, binaryfile);
besides that you also have wrong sizeof()
it shouldn't be sizeof(&MyRec..)
it should be sizeof(MyRec..)
without &
.
Upvotes: 3