C fsetpos() Function Tutorial

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

C fsetpos() Function

Sometimes when we open a file and start to read and write on it, we want to change the current position where the read or write is happening in order to get a different part of the target file.

This is where we can use the `fsetpos()` function.

C fsetpos() Function Syntax:

Here’s the prototype of the function:

int fsetpos(FILE *stream, const fpos_t *pos)

C fsetpos() Function Parameters

The function takes two arguments:

The first one is the address of the memory space allocated to the FILE-structure of the target file.

The second argument is the position that we want to start to read/write from there on the target file.

Note: the type of the second argument is `fpos_t`.

C fsetpos() Function Return Value

In a successful operation, the returned value of the function is 0 and on failed operation it will return a non-zero value.

Example: using fsetpos() function in C

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


int main() {

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

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

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

    }

    fclose(file);

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

Output:

is John Doe

Done

Note: the actual content in the file was “Hello this is John Doe” but because we pushed the current position 10 elements forward, the “Hello this” part is left behind and the rest of the content was read and printed on the display.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies