1
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?

Lynn
  • 10,425
  • 43
  • 75
  • What, specifically, is the misbehavior you observe? – John Bollinger Nov 25 '15 at 21:51
  • 2
    But do note that your use of `feof()` is incorrect; see http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – John Bollinger Nov 25 '15 at 21:52
  • Can you clarify whether you are trying to read a single student, or you are trying to read all the students from the file? – M.M Nov 25 '15 at 21:53
  • ...in any case it would be `while (!feof(test))` but as commented either way is wrong. – Weather Vane Nov 25 '15 at 21:54
  • in general, never use `feof()` for loop control. In this case use the returned value from the call to `fread()` to control the loop. The man page for `fread()` has the details on the returned value – user3629249 Nov 26 '15 at 10:53
  • when calling `fopen()`, always check (!=NULL) the returned value to assure the operation was successful – user3629249 Nov 26 '15 at 10:53
  • this line: `Class[i] = st;` is only going to place a pointer to `st` in `Class[i]`. Suggest using `memcpy( Class[i], st, sizeof(student) )'` – user3629249 Nov 26 '15 at 10:57
  • always check the returned value from a call to `fread()` to assure the operation was successful. (if use `fread()` in while statement, it is the returned value that will actually control the loop) – user3629249 Nov 26 '15 at 10:58
  • in the posted code, the variable `Class[]` is not defined. can we assume it is an array of `student`? – user3629249 Nov 26 '15 at 11:00

1 Answers1

2

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;
}
Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365