Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is rewind() in C?

Kainat Asif

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The rewind() function in C is used to set the file pointer to the start of the file. The declaration of the rewind() function is shown below:

void rewind( File * stream);

Parameter

  • stream: Pointer to the file to set file pointer to beginning.

Example

Consider the code snippet below, which uses rewind() to set the file pointer of a file to the beginning:

main.c
rewindExample.txt
#include <stdio.h>
int main() {
FILE * fPointer;
char str[100];
fPointer = fopen ("rewindExample.txt", "r");//opening file
fgets(str, 100, fPointer);
printf("%s",str);
fgets(str, 100, fPointer);
printf("%s",str);
rewind(fPointer);
fgets(str, 100, fPointer);
printf("%s",str);
fclose(fPointer);
return 0;
}

Explanation

The contents of rewindExample.txt are as follows:

This is line 1.
This is line 2.
This is line 3.
  • The first time we use fgets() in line 10, it reads the first line of the file and increments the file pointer so that when we apply a read operation to the file after this, it starts reading from the second line.
  • The second time we use fgets() in line 13, it reads the second line of the file.
  • The third time we use fgets() in line 18, it should read the third line of the file. But since we use rewind() in line 16, the file pointer will be set to start of the file and the first line will be printed.

RELATED TAGS

c

CONTRIBUTOR

Kainat Asif
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring