Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between fgets and fscanf?

Tags:

c

fgets

scanf

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?

like image 507
Chris Avatar asked Jan 18 '12 21:01

Chris


2 Answers

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)
like image 136
cnicutar Avatar answered Oct 13 '22 10:10

cnicutar


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

like image 7
Carl Norum Avatar answered Oct 13 '22 10:10

Carl Norum