Example (fsetpos -- Set File Position)

This example opens a file for reading. After performing input operations (not shown), fsetpos moves the file pointer to the beginning of the file and rereads the first byte.

#include <stdio.h>
#define FILENAME "myfile.dat"
FILE *stream;
int main(void)
{
   int retcode;
   fpos_t pos, pos1, pos2, pos3;
   char ptr[20];  /* existing file 'FILENAME' has 20 byte records */
   /* Open file, get position of file pointer, and read first record */
   stream = fopen("FILENAME", "rb");
   fgetpos(stream,&pos);
   pos1 = pos;
   if (!fread(ptr,sizeof(ptr),1,stream))
       perror("fread error");
   /* Perform a number of read operations
       - the value of 'pos' changes       */
   /* Re-set pointer to start of file and re-read first record */
   fsetpos(stream,&pos1);
   if (!fread(ptr,sizeof(ptr),1,stream))
       perror("fread error");
   fclose(stream);
   return 0;
}