Share on Google+Share on Google+

C file fgetpos() function

This section demonstrates you the use of fgetpos()function.

C file fgetpos() function

This section demonstrates you the use of fgetpos() function. This function get the current read/write position of stream and stores the information in the pos object. This information is used by the fsetpos() function to return to the same position.

Its syntax is: fgetpos(File *stream, fpos_t *pos)

The fgetpos() function identify the current value of the given stream's position indicator and stores it in the location pointed by position. The position variable of type fpos_t can hold every possible position in a FILE. In the following code, the function fopen(file, "r") open the specified file and allow to perform read operations. The specified file is having the data "Hello World". The fgetpos() function stores the information in pos object which is used by the fsetpos() function. The fgetc() function display the next character from the string.

Here is the code:

#include <stdio.h>
#include <conio.h>

int main() {
      FILE * pFile;
      int c;
      int n;
      fpos_t pos;
      pFile = fopen("myfile.txt", "r");
      if (pFile == NULL)
          perror("Error opening file");
     else {
          c = fgetc(pFile);
          printf("1st character is %c\n", c);
          fgetpos(pFile, &pos);
          fsetpos(pFile, &pos);
          c = fgetc(pFile);
          printf("2nd character is %c\n", c);
          c = fgetc(pFile);
          printf("3rd character is %c\n", c);
          c = fgetc(pFile);
          printf("4th character is %c\n", c);
          c = fgetc(pFile);
          printf("5th character is %c\n", c);


1st character is H
2nd character is e
3rd character is l
4th character is l
5th character is o



Posted on: December 26, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.