Name

fgetpos

Synopsis

Obtains the current read/write position in a file

#include <stdio.h>
intfgetpos( FILE * restrict fp, fpos_t * restrict ppos );

The fgetpos() function determines the current value of the file position indicator in an open file, and places the value in the variable referenced by the pointer argument ppos. You can use this value in subsequent calls to fsetpos() to restore the file position.

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.

The fgetpos() function returns 0 if successful. If an error occurs, fgetpos() returns a nonzero return value and sets the errno variable to indicate the type of error.

Example

FILE *datafile; fpos_t bookmark;

if ((datafile = fopen(".testfile", "r+")) == NULL)
{
  fprintf( stderr, "Unable to open file %s.\n",".testfile" );
  return 1;
}

if (fgetpos( datafile, &bookmark ))    // Save initial position
  perror( "Saving file position" );
else
{
  /* ... Read data, modify data ... */

  if ( fsetpos( datafile, &bookmark ))    // Return to initial position
    perror( "Restoring file position" );

  /* ... write data back at the original position in the file ... */
}

Get C in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.