In K&R2 fscanf() is reported to return EOF in case of error. However
when I use it in the style:
fscanf(stdin, "%d", &x)
and enter a character, it returns 0 and not EOF. When which
circumstances does it return EOF and when 0?
The scanf engine -- the thing that implements scanf and fscanf (and
even sscanf except that some concepts no longer apply) -- has two
kinds of "failure": an "input failure" and a "matching failure".
(This is spelled out in the C Standard, so all implementations
do this, or at least, are required to work "as if" they had the
two kinds of failure.)
"Input failure" occurs when getc(stream) returns EOF. This in
turn implies that feof(stream) or ferror(stream) (or perhaps even
both) will be nonzero.
"Matching failure" occurs only when getc(stream) succeeds, but
the character obtained cannot be matched against the current
directive.
The return value from fscanf() is EOF only in the event of input
failure, and even then, only if the input failure occurs before
any "conversion". Conversions are the things introduced with "%"
(apparently including %n).
A question for the Standards Interpreters: if the format argument
to a scanf-family directive *begins* with %n, does that mean that
this call can never return EOF? For instance, is:
int x;
char c;
while (scanf("%n%c", &x, &c) != EOF)
continue;
always an infinite loop? (The reasoning here is that %n is a
successful conversion, always storing 0 into x, and then the %c
"eats" characters until EOF -- but at that point, each EOF occurs
after one %n "conversion", since %n does not start by reading
characters from the stream.)