I want to know what is the difference between fgets()
and scanf()
. I am using C as my platform.
The main difference lies in the fact that scanf
has no limits on the number of characters that can be read (in its default use), while fgets
has a maximum number of char that can be read.
See the prototype of the two functions:
char * fgets (char * dest, int size, FILE * stream);
int scanf (const char * format, ...);
You can see that the second parameter of fgets
imposes to read at most size char.
Another clear difference is the return value: fgets
return a pointer to dest
on success; scanf
return the number of input items successefully matched and assigned.
Then, the scanf function scans input according to format, and reads input from the standard input stream stdin, while fgets
reads input from FILE * stream as default.
In conclusion, you could use scanf
to read data from a FILE and insert them into a fixed-size array (for example) does not have much sense.
An advantage of scanf
is the formatting of output data: if the function reads 12345\n
, the output is 12345
, while the fgets reads and returns till \n
(included), adding a \0
in the end as a string terminator.