Difference between fgets and fscanf?

I have a question about fgets and fscanf in C. What is the difference between the two? For instance:

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

and second example:

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

if there is a text file that contains lines separated by white space, for example: AB1234 AC5423 AS1433. In the first example, the “counter” in the while loop will not produce the same result as in the second example. If you change "10" in the fgets function, the counter will always give different results. What is the reason for this? Can someone please also explain what exactly fscanf does, how long is the line in each while loop?

+5
source share
4 answers

fgets ( ). fscanf %s ...

scanf, . :

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

fgets . fscanf .

+3

fgets . fscanf %s , (\n,\t ..). , , , , , , . When changing the "10" in the fgets function the counter will always give different results. , fgets scanf , . . "10" , .

+1

fgets 9 str 0. . , ( str) EOF .

fscanf %s , , str, 0-. EOF. , , .

So, imagine that the input stream is as follows: "\t abcdef\n<EOF>". If you used fgetsto read, strwill contain "\t abcdef\n\0". If you used fscanf, it strcould contain "abcdef\0"(where \0denotes a 0-terminator).

+1
source

All Articles