What can happen with fgets ?
- it returns
NULL when there is an input error - it returns
NULL when it finds EOF before any "real" characters - returns a pointer to a buffer
- buffer was not full
- the buffer was full, but there is no more data in the input
- the buffer was full and more data was input
How can you distinguish between 1 and 2 ?
with feof
How can you distinguish 3.1. , 3.2. and 3.3.
Determining where the final null byte and line break were written:
If the output buffer has '\n' , then there is no more data (the buffer can be full)
If there is no '\n' AND , then '\0' is in the last position of the buffer, then you know that more data was expected; if '\0' is before the last position of the buffer, you will press EOF in the stream, which does not end with a line break.
like this
if (fgets(buf, sizeof buf, stdin)) { buflen = strlen(buf); if (buflen) { if (buf[buflen - 1] == '\n') { puts("no more data (3.1. or 3.2.)"); } else { if (buflen + 1 == sizeof buf) { puts("more data waiting (3.3.)"); } else { puts("EOF reached before line break (3.1.)"); } } } else { puts("EOF reached before line break (3.1.)"); } } else { if (feof(stdin)) { puts("EOF reached (2.)"); } else { puts("error in input (1.)"); } }
Common, incomplete tests: buf[buflen - 1] == '\n' and checking the return value of fgets ...
while (fgets(buf, sizeof buf, stdin)) { if (buf[strlen(buf) - 1] != '\n') ; }
source share