fseek() vs rewind() in C


fseek()

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

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("
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

In the above program, file “demo.txt” is opened using fopen() and fseek() function is used to move the pointer to the end of the file.

f = fopen("demo.txt", "r");
if(f == NULL) {
   printf("
Can't open file or file doesn't exist.");    exit(0); } fseek(f, 0, SEEK_END);

rewind()

The function rewind() is used to set the position of file to the beginning of given stream. It does not return any value.

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

void rewind(FILE *stream);

Here is an example of rewind() in C language,

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

This is demo!
This is demo!

Now, let us see the example.

Example

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

Output

The size of file : 28 bytes

In the above program, file is opened by using fopen() and if pointer variable is null, it will display can’t open file or file doesn’t exist. The function rewind() is moving the pointer to the starting of file.

f = fopen("new.txt", "r");
if(f == NULL) {
   printf("
Can't open file or file doesn't exist.");    exit(0); } rewind(f);

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements