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);
stream
: Pointer to the file to set file pointer to beginning.Consider the code snippet below, which uses rewind()
to set the file pointer of a file to the beginning:
#include <stdio.h>int main() {FILE * fPointer;char str[100];fPointer = fopen ("rewindExample.txt", "r");//opening filefgets(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;}
The contents of rewindExample.txt
are as follows:
This is line 1.
This is line 2.
This is line 3.
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.fgets()
in line 13, it reads the second line of the file.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.Free Resources