C File I/O Operations : rewind()

The rewind() function is used to resets the file pointer position to the beginning of the file specified as its argument. In simple words it simply rewinds the file. The syntax for rewind() file is :
 void rewind(FILE *fp);
Where fp is a file pointer. Also note that the function rewind() does not return any value.

Example :
#include <stdio.h>

int main() {
  char str[] = ("Hello world, This is Sample Text.\n");
  char str2[100];
  int len = sizeof(str);
  FILE *fp = fopen("myfile.txt", "w+");
  fputs(str, fp);
  printf("String written into myfile.txt.\n");

  rewind(fp);
  printf("Content of file :\n\n");
  fgets(str2, 100, fp);
  printf("%s", str2);
  return 0;
}
Output :

String written into myfile.txt.
Content of file :

Hello world, This is Sample Text.

At above example first the string is written  into a text file and then rewind() is used to reset the file pointer (fp) at the beginning of the file and prints the written string data. Also note that at fopen() function, the file is opened with "w+" mode.

Topics :