This is probably old ground to experienced users, but I've never read a solution or workaround. I have a construct:The problem is that feof remains false if the input file ends with 0D 0A (CRLF), so I get no indication that I'm on the last record. I need to know "in advance" that there are no records following. Now without the ending CRLF, feof "signals" that the next fgets will fail, and I know I'm on the last record. You can see this for yourself with an input file consisting of 1 total byte as the letter A, and then doing it with a CRLF for a file size of 3. feof reports that "the end is near!" only on the 1 byte case.Code:while(fgets...) { if (feof }
This is all just to illustrate what I know is by design; fgets() doesn't see a newline character in the 1-byte-file case, so indeed you have hit EOF once it fires. In the 3-byte-file case, fgets got his newline character and stopped then. The program doesn't know if there's more following, because fgets stopped when he got his newline, and didn't need to look any further; even though he's literally on the doorstep of EOF, an according-to-Hoyle EOF has not occurred.
So here is what this is leading to. I want to know, within the fgets loop, if EOF is imminent. I can't rely on feof as described before; it gives a different result depending if the file ends with newline. Obviously it would be atrocious to "peek" with an extra fgets and rewind. So what is the civilized best coding practice solution? All I've come up with isBut that's so unclean!Code:while(fgets...) { if (icount>0) { /* process the PRIOR pass of fgets which I've buffered away */ } /* Now buffer away the the CURRENT pass of fgets */ } /* Now process the final pass of fgets after the loop fails. I will give special treatment to the final record, so different code here. */