The Wayback Machine - https://web.archive.org/web/20240118170215/https://www.geeksforgeeks.org/fseek-in-c-with-example/
Open In App
Related Articles

fseek() in C/C++ with example

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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

Syntax of fseek()

The fseek() syntax is:

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

Parameters

  • pointer: It is the pointer to a FILE object that identifies the stream.
  • offset: It is the number of bytes to offset from the position
  • position: It is the position from where the offset is added. Position defines the point with respect to which the file pointer needs to be moved. It has three values:
    • SEEK_END: It denotes the end of the file.
    • SEEK_SET: It denotes starting of the file.
    • SEEK_CUR: It denotes the file pointer’s current position. 

Return Value

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

Example

The below C Program demonstrates the use of fseek() function.

C




// 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;
}


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.

Related Articles:

Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 06 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads