fsetpos C Library Function

The stdio C library function int fsetpos(FILE *stream, const fpos_t *pos); sets the current position in the stream to the position represented by pos. The argument pos is a pointer of type fpos_t object whose value was previously obtained by a call to fgetpos function.

Function prototype of fsetpos

int fsetpos(FILE *stream, const fpos_t *pos);
  • stream : A pointer to a FILE object which identifies a stream.
  • pos : This is a Pointer to a fpos_t object containing a position previously obtained by calling fgetpos function.

Return value of fsetpos

This function returns zero on success. In case of error it returns a non-zero value and sets the global variable errno to a system-specific positive value.

C program to show the use of fsetpos function

The following program shows the use of fgetpos function to get the position of first character in file and store it in a variable of type fpos_t. Later we will use this value to reset the file position indicator to point to first character of the file using fsetpos function. As a result, below program first prints the first four characters of the file then it again starts printing from the first character of the file.

fsetpos C Library Function

#include <stdio.h>
 
int main(){
   FILE *file;
   int ch, counter;
   fpos_t position;
 
   file = fopen("textFile.txt","r");
   if (file==NULL){
       perror("Error: Unable to open a file");
       return(1);
   }
   /* Storing position of first character in file */
   fgetpos(file, &position);
    
   for (counter = 0; counter < 23; counter++){
       if(counter == 4){
       /* Resetting file position pointer to starting position*/
           fsetpos(file, &position);
       }
       ch = fgetc(file);
       printf("%c",ch);
   }   
   fclose(file);
 
   return 0;
}

Output

TechTechCrashCourse.com