0

consider

while(!feof(f)){/**do something**/}

I've read that this is wrong, because it executes the loop also one extra time. Can someone explain why? Seems to me that when the end of the file is reached, feof(f) returns true and so the loop does not get executed one more time. I've tried this and it's working correctly on my machine.

I was redirected from my previous question to a discussion about this.

As seems like that lots of experts considers this wrong, but it's also evident to me that this works in my case, can someone provide a short example in which this works and another in which this doesn't, motivating it?

Thank you.

waddafunk
  • 3
  • 1
  • 4
  • @Pablo I went through this already, my problem is that it works just fine in my case, i would like some examples to understand better. – waddafunk Jan 17 '20 at 01:22
  • 1
    It depends on the system as to whether reading the last character of the file sets the eof flag or not – M.M Jan 17 '20 at 01:22
  • So this works fine on some machines but not on every machine? – waddafunk Jan 17 '20 at 01:26
  • If you're reading ints (e.g. scanf %d) try having the file end with a number followed by whitespace – M.M Jan 17 '20 at 01:29
  • No actually i was reading chars, anyway i think I got it, there are better ways. Thank you. – waddafunk Jan 17 '20 at 01:36
  • Fun fact: our teachers at the university teach us to use this – waddafunk Jan 17 '20 at 01:41
  • 1
    Most university C and C++ courses suck , they re-use old material (that may have always been wrong) without any effort to understand or improve it. No doubt they will also teach you to cast malloc, and that arrays are const pointers – M.M Jan 17 '20 at 01:43
  • Short answer, `feof` tells you if the *previous* read failed. It is not supposed to tell you anything about the next read. Predicting the future is difficult. Looking at the past, not so much. – HAL9000 Jan 17 '20 at 09:13

0 Answers0