C Standard Library

C <stdio.h> - fgetpos() Function



The C <stdio.h> fgetpos() function obtains the file position indicator and the current parse state (if any) for the file stream stream and stores them in the object pointed to by position. The content stored in position can be used as an argument in fsetpos() function, and not meant to be read directly.

Syntax

int fgetpos( FILE* stream, fpos_t* position );

Parameters

stream Specify a pointer to a FILE object that identifies the stream.
position Specify a pointer to a fpos_t object to store the file position indicator.

Return Value

On success, returns zero. On failure, returns non-zero value and sets errno to a system-specific positive value.

Example:

In the example below, program creates an empty file for output operations if the file test.txt does not exist. If the file already exists, its contents are discarded and the file is treated as a new empty file.

First, initial position of the file is get using fgetpos() function and then "Hello World!." is written to it. Then the position of the file is set to start using fsetpos() function to display the content of the file.

#include <stdio.h>
 
int main (){
  //open the file in write and read mode
  FILE * pFile = fopen("test.txt","w+");
  fpos_t position;
  int c;

  //get the beginning position
  fgetpos(pFile, &position);
  fputs("Hello World!.", pFile);

  //set the position to the start
  fsetpos(pFile, &position);

  //display the content of the file
  c = getc(pFile);
  while(c != EOF) {
    putchar(c);
    c = getc(pFile);
  }

  //close the file
  fclose (pFile);

  return 0;
}

The output of the above code will be:

Hello World!.

❮ C <stdio.h> Library