The function int fgetpos(FILE *stream, fpos_t *position); stores the value of the file position indicator(current position in the stream) in the object pointed to by position. The value stored in position can be used in subsequent call to fsetpos function.
Function prototype of fgetpos
int fgetpos(FILE *stream, fpos_t *position);
- stream : A pointer to a FILE object which identifies a stream.
- position : The object pointed by position must be of type fpos_t. Function fgetpos stores the current position of the stream in this object.
Return value of fgetpos
This function returns zero on success otherwise it returns a non-zero value If an error occurs.
C program using fgetpos function
The following program shows the use of fgetpos function to reset the file position indicator. Let file “textFile.txt” contains “TechCrashCourse.com” string. In below program, we first save the position of first character of the file using fgetpos function, then we reset the file position indicator to point to first character every time using fsetpos function, such that it prints first character every time.
#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 < 5; counter++){ fsetpos(file, &position); ch = fgetc(file); printf("First Character is : %c\n",ch); } fclose(file); return 0; }
Output
First Character is : T First Character is : T First Character is : T First Character is : T First Character is : T