fseek() in C (original) (raw)

Last Updated : 2 Aug, 2025

The fseek() function is used to move the file pointer associated with a given file to a specific location in the file. It provides random access capabilities, which allow the programmer to randomly move the file pointer to any location in the file to read or write data.

Syntax of fseek()

The fseek() function is declared in the <stdio.h> header file.

C `

int fseek(FILE *pointer, long int offset, int position);

`

Parameters

Return Value

Examples of fseek()

The following programs demonstrate the use of fseek() function in our C programs:

Move File Pointer to End of File

C `

#include <stdio.h>

int main() { FILE* fp; fp = fopen("test.txt", "r");

// Moving pointer to end
fseek(fp, 0, SEEK_END);

// Printing position of pointer
printf("%ld", ftell(fp));

return 0;

}

`

**Suppose the file test.txt contains the following data:

"Someone over there is calling you.
we are going for work.
take care of yourself."

**Output

81

**Explanation

When we implement fseek(), we move the pointer by 0 distance with respect to the end of the file i.e. pointer now points to the end of the file. Therefore the output is 81.

**Move File Pointer to Start of File

C `

#include <stdio.h>

int main() { FILE* fp; fp = fopen("test.txt", "r");

// Moving pointer to start
fseek(fp, 0, SEEK_SET);

// Printing position of pointer
printf("%ld", ftell(fp));

return 0;

}

`

**Suppose the file test.txt contains the following data:

"Someone over there is calling you.
we are going for work.
take care of yourself."

**Output

0

**Explanation

In the above program we use fseek() to move the pointer by 0 distance with respect to the start of the file i.e. the pointer now points to the start of the file. Thus the current position fo the pointer is 0, Therefore the output is 0.