0

which of these codes is better?

do {
 fread( ... );
 if(!feof(fp)) { ... }
}
while(!feof(fp));

or

while(1){
  fread( ... );
  if(!feof(fp)) { ... }
  else break;
}

Thanks.

Mike L
  • 1,795
  • 2
  • 15
  • 16

3 Answers3

2

Neither. You are better off making the eof test part of the loop condition (at the top).

You can do this:

while (!feof(fp)) {
    fread(...);
}

Since fread returns the number of objects read, you could should also do it this way:

while (fread(...) != 0) {
}
Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
Ferruccio
  • 96,346
  • 38
  • 221
  • 297
1

The while loop is better since the do while do the same operations but it's calling the feof() function twice.

rullof
  • 6,656
  • 5
  • 23
  • 34
  • You shouldn't call the function twice as it could be changing! You could declare a variable to store the returned value to check it but the `while` still better – rullof Dec 28 '13 at 17:16
0

which is better?

No one is better than another. The only difference in between these two that first one iterate at least once.

haccks
  • 100,941
  • 24
  • 163
  • 252