C programming fsetpos stdio.h

In C programming the <stdio.h> fsetpos function set the file indicator position to the specified position.This function provides a way to point the file indicator to any position and thus allowing easy manipulation of the file.The declaration of the function is given below.

int fsetpos(FILE *stream , const fpos_t *pos);

stream -The pointer to the file whose indicator is to be set.

pos -A ‘fpos_t’ type which is the value obtained by calling ‘fgetpos’ function.

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

Link : C fgetpos stdio.h

If a read or write error occurs the error indicator for the stream is set and ‘fsetpos’ fails.

A code example is given below.To understand the program below consider a ‘text.txt’ file with the content “0123456789defgh“.

Code example

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

int val, ret, count = 1;

fpos_t pos;

if (fp != NULL)
//access the first 10 characters
while( (val = fgetc( fp )) != EOF )
printf(“%c” , val);
if (count == 10)
fgetpos(fp , &pos); //get the position of the 11th position
printf(“File cannot be opened”);


fp = fopen(“text.txt”, “r+”);

//set the file indicator to the 11th position
ret=fsetpos(fp , &pos);

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

fputs(” 10th position ” , fp); //writes the string after the 10th character





Now open the file “text.txt” the content is changed to “0123456789 10th position efgh“,as you can see the string ” 10th position ” is written after the 11th character.

Some points to note

i)A successful call to fsetpos

A successful call to the ‘fsetpos’ function undoes any effects of the ‘ungetc’ function on the stream, clears the end-of-file indicator for the stream, and then establishes the new parse state and position.After a successful ‘fsetpos’ call,the next operation on an update stream may be either input or output.

Link : C funget stdio.h

Related links

->C rewind stdio.h

->C fputs stdio.h

->C fopen stdio.h