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,955
  • 2
  • 16
  • 18

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
  • 730,956
  • 141
  • 904
  • 1,278
Ferruccio
  • 98,941
  • 38
  • 226
  • 299
1

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

rullof
  • 7,124
  • 6
  • 27
  • 36
  • 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
  • 104,019
  • 25
  • 176
  • 264