C++ fgetpos()

The fgetpos() function in C++ gets the current file position indicator.

fgetpos() prototype

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

The fgetpos() function obtains the file position indicator and the current parse state for the given file stream. The result is stored in the object pointed by pos.

It is defined in <cstdio> header file.

fgetpos() Parameters

  • stream: The file stream whose file position indicator is returned.
  • pos: A pointer to fpos_t object to store the file position indicator.

fgetpos() Return value

  • On success, the fgetpos() returns zero.
  • On failure it returns non-zero value and sets errno.

Example: How fgetpos() function works

#include <cstdio>

int main()
{
    FILE *fp;
    fpos_t pos;
    int c;
    
    fp = fopen("myfile.txt","w+");
    
    /*  Get the beginning position  */
    fgetpos(fp, &pos);
    fputs("What a great day!",fp);
    
    /*  Set the position to the start  */
    fsetpos(fp, &pos);
    
    while(!feof(fp))
    {
        c = getc(fp);
        putchar(c); 
    }
    
    fclose(fp);
    return 0;
}

When you run the program, the content of buffer will be written to the file and the output will be:

What a great day!