fgetpos Function

Gets the stream’s file position.

Attention: This function is not implemented by MPLAB XC8.




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


target stream
position-indicator storage

Return Value

Returns 0 if successful; otherwise, returns a non-zero value.


The function stores the file-position indicator for the given stream into the object pointed to by pos if successful; otherwise, fgetpos sets errno.


See the notes at the beginning of this chapter or section for information on using printf() or scanf() (and other functions reading and writing the stdin or stdout streams) in the example code.

/* This program opens a file and reads bytes at */
/* several different locations. The fgetpos     */
/* function notes the 8th byte. 21 bytes are   */
/* read then 18 bytes are read. Next the        */
/* fsetpos function is set based on the         */
/* fgetpos position and the previous 21 bytes   */
/* are reread.                                  */

#include <stdio.h>

int main(void)
  FILE   *myfile;
  fpos_t pos;
  char   buf[25];

  if ((myfile = fopen("sampfgetpos.c", "rb")) == NULL)
    printf("Cannot open file\n");
   fread(buf, sizeof(char), 8, myfile);
    if (fgetpos(myfile, &pos) != 0)
      perror("fgetpos error");
      fread(buf, sizeof(char), 21, myfile);
      printf("Bytes read: %.21s\n", buf);
      fread(buf, sizeof(char), 18, myfile);
      printf("Bytes read: %.18s\n", buf);

  if (fsetpos(myfile, &pos) != 0)
    perror("fsetpos error");

  fread(buf, sizeof(char), 21, myfile);
  printf("Bytes read: %.21s\n", buf);

Example Output

Bytes read: program opens a file
Bytes read: and reads bytes at
Bytes read: program opens a file