If you want to scan digit by digit, you need to use "%1d"
as the format.
Otherwise, it reads the whole line (apart from the newline) as the number and invokes undefined behaviour when it converts the large decimal number into a 32-bit int
. Note that the mnemonic for d
is not 'digit' but 'decimal', as opposed to 'o' for octal, 'x' for hexadecimal, and 'i' for integer in decimal, octal or hexadecimal according to the normal prefixes (leading 0
for octal, 0x
for hex, or decimal otherwise).
It is still not entirely clear why it returns EOF, but with undefined behaviour, any response is valid.
The standard (ISO/IEC 9898:2011 Section 7.21.6.2 The fscanf()
function, Para 10) says (in the relevant part):
If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.
There is quite a lot of verbiage about the behaviour under error conditions, but this is the crucial one here. Since the behaviour is undefined, getting EOF is a valid and relatively benign response. It would be interesting to investigate whether the file stream is in the state where feof(f)
or ferror(f)
returns true. There's no obvious reason why it should be except that you do not normally get EOF from fscanf()
unless one or the other is true.