Difference between fgets and fscanf? Difference between fgets and fscanf? c c

Difference between fgets and fscanf?


The function fgets read until a newline (and also stores it). fscanf with the %s specifier reads until any blank space and doesn't store it...

As a side note, you're not specifying the size of the buffer in scanf and it's unsafe. Try:

fscanf(ptr, "%9s", str)


fgets reads to a newline. fscanf only reads up to whitespace.


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).