Reputation: 6233
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?
Upvotes: 18
Views: 72210
Reputation: 182639
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)
Upvotes: 17
Reputation: 123468
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).
Upvotes: 6
Reputation: 5456
fgets
read the whole line. fscanf
with %s
read a string, separate by space (or \n,\t,etc...).
Anyway, you should not use them unless you sure that the array you read to is big enough to contain the input.
You wrote When changing the "10" in the fgets function the counter will always give different results.
Note that fgets and scanf don't know how much bytes to read. you should tell them. changing the "10" just enlarge the buffer these functions write to.
Upvotes: 2
Reputation: 224944
fgets
reads to a newline. fscanf
only reads up to whitespace.
Upvotes: 6