fseek() in C/C++

CC++Programming

fseek() in C language, is use to move file pointer to a specific position. Offset and stream are the destination of pointer, is given in the function parameters. If successful, it returns zero. If it is not successful, it returns non-zero value.

Here is the syntax of fseek() in C language,

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

Here are the parameters used in fseek()

  • stream − This is the pointer to identify the stream.

  • offset − This is the number of bytes from the position.

  • whence − This is the position from where offset is added.

whence is specified by one of the following constants.

  • SEEK_END − End of file.

  • SEEK_SET − Starting of file.

  • SEEK_CUR − Current position of file pointer.

Here is an example of fseek() in C language.

Let’s say we have “demo.txt” file with the following content −

This is demo text!
This is demo text!
This is demo text!
This is demo text!

Now let us see the code.

Example

#include<stdio.h>
void main() {
   FILE *f;
   f = fopen("demo.txt", "r");
   if(f == NULL) {
      printf("\n Can't open file or file doesn't exist.");
      exit(0);
   }
   fseek(f, 0, SEEK_END);
   printf("The size of file : %ld bytes", ftell(f));
   getch();
}

Output

The size of file : 78 bytes
raja
Published on 08-Oct-2018 09:39:36
Advertisements