rewind file function in c

27 Dec 2022 Balmiki Mandal 0 C Programming

what is rewind function in c?

In C, there is no built-in function to rewind a file. However, you can use the fseek() function to set the file position indicator to the beginning of the file. 

Here's an example of how you can use the fseek() function to rewind a file:

#include <stdio.h>

int main() {
   FILE *fp;
   char c;

   fp = fopen("example.txt", "r");
   if (fp == NULL) {
      printf("Failed to open file.\n");
      return 1;
   }

   // read the file
   while ((c = getc(fp)) != EOF) {
      printf("%c", c);
   }

   // rewind the file
   fseek(fp, 0, SEEK_SET);

   // read the file again from the beginning
   while ((c = getc(fp)) != EOF) {
      printf("%c", c);
   }

   fclose(fp);

   return 0;
}

Attention: In this example, the fseek() function is called with the file pointer (fp), an offset of 0, and the SEEK_SET flag to set the file position indicator to the beginning of the file. After rewinding the file, we can read it again from the beginning. Note that the rewind() function is equivalent to fseek(fp, 0, SEEK_SET).

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.