C Library - rewind() function



The C library void rewind(FILE *stream) function sets the file position to the beginning of the file of the given stream.This is particularly useful when you need to re-read the content of the file from the start after having performed read/write operations.

Syntax

Following is the C library syntax of the rewind() function −

void rewind(FILE *stream);

Parameters

This function accepts only a single parameter −

  • FILE stream: This is a pointer to a FILE object that identifies the stream. The FILE object is typically obtained from the fopen function, which opens the file and associates it with the stream.

Return Value

The rewind function does not return a value. It performs the operation silently. If the operation fails, it sets the file position indicator to the beginning of the file and clears the end-of-file and error indicators for the stream.

Example 1: Re-reading a File

This example shows how to read a file, use rewind to reset the position indicator, and read the file again.

Below is the illustration of the C library rewind() function.

#include <stdio.h>

int main() {
   FILE *file = fopen("example.txt", "r");
   char ch;

   if (file == NULL) {
       perror("Error opening file");
       return 1;
   }

   printf("First read:\n");
   while ((ch = fgetc(file)) != EOF) {
       putchar(ch);
   }

   rewind(file);

   printf("\n\nSecond read after rewind:\n");
   while ((ch = fgetc(file)) != EOF) {
       putchar(ch);
   }

   fclose(file);
   return 0;
}

Output

The above code produces following result−

First read:
Hello, World!
This is a test file.

Second read after rewind:
Hello, World!
This is a test file.

Example 2: Using rewind in Binary File Operations

This example shows the use of rewind in handling binary files.

#include <stdio.h>

int main() {
   FILE *file = fopen("binary.dat", "wb+");
   int numbers[] = {1, 2, 3, 4, 5};
   int read_numbers[5];

   if (file == NULL) {
       perror("Error opening file");
       return 1;
   }

   fwrite(numbers, sizeof(int), 5, file);

   rewind(file);

   fread(read_numbers, sizeof(int), 5, file);

   printf("Reading numbers after rewind:\n");
   for (int i = 0; i < 5; i++) {
       printf("%d ", read_numbers[i]);
   }

   fclose(file);
   return 0;
}

Output

After execution of above code, we get the following result −

Reading numbers after rewind:
1 2 3 4 5 
Advertisements