Example of fseek() in C

Introduction to fseek() in C:

This method is used to change the position of the position indicator for a stream pointer. After opening a file, we can change the position of the file pointer associated with that file.

Definition of fseek():

This method is defined as below:

int fseek ( FILE * ptr, long int offset, int origin );

Here,

  • ptr is the stream pointer to a file.
  • offset is the offset to add from origin in bytes.
  • origin is the origin position used as the reference for the offset.

It can be any of the following constant values:

SEEK_SET : Used to define the beginning of the file SEEK_CUR : Current position of the file pointer SEEK_END : End of the file

One thing we should keep in mind that it works differently for binary mode and text mode operations. For binary mode, it adds the offset to the origin value to find out the next position. But for text mode, origin shall necessarily be SEEK_SET and origin shall be 0 or a value returned by a previous call to ftell. reference

For success, it returns 0 and for failure, it returns other non-zero values.

Example of fseek():

Let’s take a look at the below program:

#include <stdio.h>

int main()
{
  FILE *file;
  file = fopen("testfile.txt", "r");

  fseek(file, 0, SEEK_SET);
  printf("%ld\n", ftell(file));

  fseek(file, 5, SEEK_SET);
  printf("%ld\n", ftell(file));

  fseek(file, 0, SEEK_END);
  printf("%ld\n", ftell(file));

  return 0;
}

The testfile.txt contains the below line:

hello world

If you run it, it will print the below output:

0
5
11

Here,

  • The first fseek moves the pointer to start. So, it printed 0.
  • The second fseek moved to to 5 offset positions from start. So, it printed 5.
  • The third fseek moved it to the end of the file. So, it printed 11.