fseek() in C/C++ with example

fseek() is used to move file pointer associated with a given file to a specific position.

int fseek(FILE *pointer, long int offset, int position)
pointer: pointer to a FILE object that identifies the stream.
offset: number of bytes to offset from position
position: position from where offset is added.

zero if successful, or else it returns a non-zero value 

position defines the point with respect to which the file pointer needs to be moved. It has three values:
SEEK_END : It denotes end of the file.
SEEK_SET : It denotes starting of the file.
SEEK_CUR : It denotes file pointer’s current position.

// C Program to demonstrate the use of fseek()
#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;




The file test.txt contains the following text:

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

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

Related article: fseek vs rewind in C

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment



load comments

Subscribe to Our Newsletter