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 ?
From the documentation: "Reads data from the stream..." this means it will act as other stream you read from. (http://www.cplusplus.com/reference/cstdio/fscanf/)
If you go to the definition of file (FILE - go to definition) you will get to this typedef
#ifndef _FILE_DEFINED
struct _iobuf {
char *_ptr;
int _cnt;
char *_base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char *_tmpfname;
};
typedef struct _iobuf FILE;
#define _FILE_DEFINED
#endif
where you can see sevral pointer (_base & _ptr) that will imply that FILE keeps pointers to both the begining of the file (for seeks, as with any other stream) and to the current location.