Difference between fgets and fscanf?

Chris picture Chris · Jan 18, 2012 · Viewed 47.5k times · Source

I have a question concerning fgets and fscanf in C. What exactly is the difference between these two? For example:

char str[10];
while(fgets(str,10,ptr))
{
counter++;
...

and the second example:

char str[10];
while(fscanf(ptr,"%s",str))
{
counter++;
...

when having a text file which contains strings which are separated by an empty space, for example: AB1234 AC5423 AS1433. In the first example the "counter" in the while loop will not give the same output as in the second example. When changing the "10" in the fgets function the counter will always give different results. What is the reason for this? Can somebody please also explain what the fscanf exactly does, how long is the string in each while loop?

Answer

cnicutar picture cnicutar · Jan 18, 2012

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)