C programming fgetpos stdio.h

In C programming the <stdio.h> fgetpos function get the current file indicator position for the stream currently in used.The declaration of the function is given below.

int fgetpos(FILE * restrict stream ,
fpos_t * restrict pos);

stream -The stream currently in used.

pos – An ‘fpos_t’ type that stores the current file indicator position.

Return type
int -If successful returns zero;on failure,the ‘fgetpos’ function returns nonzero and stores an implementation-defined positive value in errno.

The information stored by ‘pos’ is some unspecified value usable by ‘fsetpos‘ for repositioning the stream to it’s position at the time of the call to the ‘fgetpos’ function.For the program given below consider that the ‘text.txt’ file with the content “123456789 10 11 12 13 name of the string” exist.

Code example

FILE *fp=fopen(“text” , “r+”);

int val , ret , count =1;

fpos_t pos;

while( (val=fgetc(fp)) !=EOF ) //read the text.txt file
printf(“%c” , val);
ret=fgetpos(fp , &pos); //stores the file indicator pointing to 4th character
count++ ;

printf( “\nret=%d\n” , ret );

fsetpos(fp , &pos); //set the file indicator to point to the 4th character

while( (val=fgetc(fp))!=EOF )
printf(“%c” , val); //access the 4th and the following character

fclose( fp );


123456789 10 11 12 13 14 name string
456789 10 11 12 13 14 name string

After calling ‘fsetpos’ reading the ‘fp’ stream starts from the 4th character.

*Side Note

If the FILE pointer argument refers to a multibyte stream, then the fgetpos( ) function also obtains the stream’s multibyte parsing state. In this case, the type ‘fpos_t’ is defined as a structure to hold both the file position information and the parsing state.

Link : Multibyte character wchar_t and wstring

Related links

->C fgetc stdio.h

->C fsetpos stdio.h

->C fopen stdio.h