fgetpos

From cppreference.com
< c‎ | io
 
 
File input/output


Functions
File access
(C11)
(C95)
Direct input/output
Unformatted input/output
(C95)(C95)
(C95)
(C95)(C95)
(C95)
(C95)
(C95)
(C95)
Formatted input
Formatted output
File positioning
fgetpos
Error handling
Operations on files
 

Defined in header <stdio.h>
int fgetpos( FILE          *stream, fpos_t          *pos );
(until C99)
int fgetpos( FILE *restrict stream, fpos_t *restrict pos );
(since C99)

Obtains the file position indicator for the file stream stream and stores it in pos.

Contents

[edit] Parameters

stream - file stream to examine
pos - pointer to a fpos_t object to store the file position indicator to

[edit] Return value

0 upon success, nonzero value otherwise.

[edit] Example

fgetpos with error checking

#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    /* Prepare an array of f-p values. */
    #define SIZE 5
    double A[SIZE] = {1.,2.,3.,4.,5.};
    /* Write array to a file. */
    FILE * fp = fopen("test.bin", "wb");
    fwrite(A,sizeof(double),SIZE,fp);
    fclose (fp);
 
    /* Read the f-p values into array B. */
    double B[SIZE];
    fp = fopen("test.bin","rb");
    fpos_t pos;
    if (fgetpos(fp,&pos) != 0)      /* current position: start of file */
    {
       perror("fgetpos()");
       fprintf(stderr,"fgetpos() failed in file %s at line # %d\n", __FILE__,__LINE__-3);
       exit(EXIT_FAILURE);
    }
 
    int ret_code = fread(B,sizeof(double),1,fp);   /* read one f-p value */
    /* current position: after reading one f-p value */
    printf("%.1f\n", B[0]);   /* print one f-p value */
 
    fsetpos(fp,&pos);   /* reset current position to start of file */
    ret_code = fread(B,sizeof(double),1,fp);   /* reread first f-p value */
    printf("%.1f\n", B[0]);   /* print one f-p value */
 
    return EXIT_SUCCESS; 
}

Output:

1.0
1.0

[edit] References

  • C11 standard (ISO/IEC 9899:2011):
  • 7.21.9.1 The fgetpos function (p: 336)
  • C99 standard (ISO/IEC 9899:1999):
  • 7.19.9.1 The fgetpos function (p: 302)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 4.9.9.1 The fgetpos function

[edit] See also

returns the current file position indicator
(function)
moves the file position indicator to a specific location in a file
(function)
moves the file position indicator to a specific location in a file
(function)
C++ documentation for fgetpos