Reputation: 69
FILE *test;
student st;
int i = 0;
test = fopen("example.bin", "rb");
while (feof(test))
{
fread(&st, sizeof(st),1,test);
Class[i] = st;
i++;
}
fclose(test);
So my question is how to read it, put the data in my structure and stop the loop?
Upvotes: 1
Views: 616
Reputation: 141633
See why is while(feof) always wrong.
Instead, you should loop until you fail to read a student:
while (1 == fread(&st, sizeof st, 1, test))
{
Class[i++] = st;
}
Also it would be good to make sure you don't overflow the buffer of Class
, so put in a check for i
too, e.g.:
for (i = 0; i < MAX_CLASS && 1 == fread(&st, sizeof st, 1, test); ++i)
{
Class[i] = st;
}
Upvotes: 2