C programming stdio.h function - int fgetpos(FILE *stream, fpos_t *pos)

In C programming, the stdio.h header file provides a set of functions for performing input and output operations on streams of data. One of the functions in this header file is fgetpos(), which retrieves the current file position indicator of a given file stream.

The fgetpos() function takes two arguments:

r‮e‬fer to:theitroad.com
int fgetpos(FILE *stream, fpos_t *pos);

The first argument, stream, is a pointer to a FILE object that represents the file stream to be accessed. The second argument, pos, is a pointer to a fpos_t object that will receive the current file position indicator.

The fgetpos() function retrieves the current file position indicator of the specified file stream and stores it in the fpos_t object pointed to by pos. If an error occurs, the function returns a non-zero value. Otherwise, it returns 0.

Here's an example of how to use fgetpos() to retrieve the current file position indicator of a file stream:

#include <stdio.h>

int main() {
    FILE *fp;
    fpos_t pos;

    fp = fopen("example.txt", "r");
    if (fp == NULL) {
        printf("Error opening file.\n");
        return 1;
    }

    /* Get the current file position */
    if (fgetpos(fp, &pos) != 0) {
        printf("Error getting file position.\n");
    } else {
        printf("File position: %lld\n", pos);
    }

    fclose(fp);

    return 0;
}

In the above example, the fopen() function is used to open a file named "example.txt" in read mode. The fgetpos() function is then used to retrieve the current file position indicator of the file stream, and store it in the pos variable. If an error occurs, the message "Error getting file position." is printed to the console. Otherwise, the current file position indicator is printed to the console using the %lld format specifier.