0

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 :(

2
  • Can you show us how you open binaryfile and read files? Commented Nov 21, 2011 at 12:15
  • Edited my post to add it Commented Nov 21, 2011 at 12:17

2 Answers 2

5

Hint:

sizeof(&foo)

Is not the same as:

sizeof(foo)
Sign up to request clarification or add additional context in comments.

1 Comment

It can be a number of things. 1) You haven't opened the file in binary mode (make sure "b" is specified for fopen). 2) Name might not have been null-terminated to start with (hint: create a print routine that you can call before writing the data to a file and after reading it back in, that way you could tell of the data was OK to start with).
3

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 &.

1 Comment

Thanks, removing the & in the sizeof fixed the problem :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.