C fgetpos() Function Tutorial

  • Post author:
  • Post category:C

In this section, we will learn what the fgetpos() function is and how it works in C.

C fgetpos() Function

Sometimes when we open a file and read and write on it, we want to know the current position from which we’re reading or writing to that file.

This is where the `fgetpos()` function can help.

The `fgetpos()` function is used to get the current value set for the file-position indicator in the FILE-structure of the target file.

Note: the difference between `ftell()` function and this one is the fact that `fgetpos()` is capable of getting higher values.

Note: the prototype of the function is in `stdio.h` header file and so we need to include the file in order to work with the function.

C fgetpos() Function Syntax:

Here’s the prototype of the function:

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

C fgetpos() Function Parameters

The function has two parameters:

  • The first parameter is an address of the memory space allocated to the FILE-structure of the target file.
  • The second parameter is an address of the memory-space of type `fpos_t` which is the place we store the current value of the file-position indicator.

C fgetpos() Function Return Value

In a successful operation, the returned value will be 0 and non-zero otherwise.

Example: using fgetpos() function in C

#include <stdio.h>
#include <stdlib.h>


int main() {


    fpos_t position;
    FILE *file = fopen("G:/fileOne.txt","r");

    if (file == NULL){
        printf("Could not open the file");
        exit(EXIT_FAILURE);

    }

    char c;
    while ((c = getc(file))!=EOF){
        fgetpos(file, &position);
        printf("%d, ",position);

    }
    
    fclose(file);

    printf("\nDone\n");
    return 0;
}

Output:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,

Done

Leave a Reply