I saw this code somewhere:
#include<stdio.h>
int main()
{
FILE * fp;
char s[1024];
fp = fopen("file","r");
while( fscanf(fp, "%s", s ) != EOF )
{
puts(s);
}
return 0;
}
I expected that this will keep on printing the first word of the file in an infinite loop. I believed that file pointer is taken as input only to get the point from where input should be read and fscanf would have a local file pointer which it would use to read the file.
But on running I realized it actually prints the whole file. Only conclusion I can draw is that after reading the first input, it actually moves the passed file pointer ahead, otherwise it would have just kept on printing the first word again and again.
I saw the man documentation of fscanf but couldnt find anything regarding movement of file pointer after reading.
Can someone please explain or give a source where it is specified that the passed file pointer actually moves after reading ?
%s
(without specifying a maximum length, such as%1023s", s
) is basically likegets
-- extremely dangerous because it does nothing to limit the input length and prevent buffer overflows. – Freeswimming