Eric said:
I wanted to limit how many chars I read in, but the code below instead
of stopping at
7 chars will happily read 30 or 40 car lines and spit them out. Not
what I expected.
#include<stdio.h>
main(){
char line [4096];
while (NULL!=fgets(line,8,stdin))
{
printf("%s",line);
}
return 0;
}
[...]
Please don't quote signatures.
I expected that if I typed 123456789 I would get 1234567 out.
I threw in a \n in the printf and it now makes some sense.
Still not behaving how I hoped having the 89 spill over is not what I
wanted, just wanted a nice safe way of inputing size limited fields.
You need to determine whether fgets() read an entire line,
or just the beginning of a line with the tail still waiting to
be read. The determination is easy, or "almost easy:" if the
buffer contains a newline character, fgets() read an entire line.
Unfortunately, the opposite is not necessarily true (this is the
"almost" part): If the buffer has no newline, either fgets()
filled the buffer and stopped with the tail of the line unread,
or fgets() encountered end-of-input without seeing a newline (on
some systems this can't happen; on others it can).
If all you want to do is discard the unread tail of any too-
long line, that's easy: When fgets() gives you no newline, just
read and discard characters until you get a newline or EOF:
while (NULL != fgets(line, 8, stdin)) {
if (strchr(line, '\n') == NULL) {
/* no newline; skip a possible tail */
int ch;
while ( (ch = getchar()) != '\n' ) {
if (ch == EOF) {
if (ferror(stdin))
/* respond to I/O error */ ;
break;
}
}
}
/* do what you will with the line (or line prefix) */
}