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.
SyntaxFollowing is the C library syntax of the rewind() function −
void rewind(FILE *stream);Parameters
This function accepts only a single parameter −
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 FileThis 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4