C fseek() Function Tutorial

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

C fseek() Function

Sometimes there’s a file like a document file that we want to read or write on it but not from the starting point of the file! For example, we want to read the content of that file starting from the middle of it. This is where we can use the `fseek()` function. Now, using this function, we can change the point from which the read or write to the file should happen.

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

C fseek() Function Syntax:

Here’s the prototype of the function:

int fseek(FILE *stream, long int offset, int whence)

C fseek() Function Parameters

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

The second parameter is the offset from which the read or write will happen.

The third parameter identifies the starting point. The value for this parameter can be one of these 3 values declared in the table below:

Mode Measures Offset From
SEEK_SET Beginning of file
SEEK_CUR Current position
SEEK_END End of file

For example: fseek(file, -10, SEEK_END);

This means, find the `file`, go to the end of that file, count 10 character towards the beginning of the file and that is the position from which the read or write should happen.

C fseek() Function Return Value

The returned value of this function if is 0 it means the operation was successful and if it was -1 it means there was an error.

Example: using fseek() function in C

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

int main() {

    //Call the the fopen function in order to open the file in read mode.
    FILE *file = fopen("G:/fileOne.txt","r");
    //if there was a problem on opening the file, exit the program.
    if (file == NULL){
        printf("Could not open the file");
        exit(EXIT_FAILURE);

    }
    fseek(file, 7 ,SEEK_SET);
    char c;
    while((c = getc(file))!=EOF){
        fprintf(stdout, "%c",c);
    }
    
    fclose(file);


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

Output:

My name is John Doe

Done

In this example, the content of the file is “Hello, My name is John Doe”. But because we set the current position to 7 elements after the starting position of the file, we’ve got the “My name is John Doe” part.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies