Difference between fgets and fscanf?
In your example, fgets
will read up to a maximum of 9 characters from the input stream and save them to str
, along with a 0 terminator. It will not skip leading whitespace. It will stop if it sees a newline (which will be saved to str
) or EOF before the maximum number of characters.
fscanf
with the %s
conversion specifier will skip any leading whitespace, then read all non-whitespace characters, saving them to str
followed by a 0 terminator. It will stop reading at the next whitespace character or EOF. Without an explicit field width, it will read as many non-whitespace characters as are in the stream, potentially overruning the target buffer.
So, imagine the input stream looks like this: "\t abcdef\n<EOF>"
. If you used fgets
to read it, str
would contain "\t abcdef\n\0"
. If you usedfscanf
, str
could contain "abcdef\0"
(where \0
indicates the 0 terminator).