Open In App

rewind() in C

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C, rewind() is a built-in function used to reset the given file pointer to the beginning of a file allowing the read and write from the beginning once again in the program without reopening the file.

Example:

C
#include <stdio.h>

int main() {
    
    FILE *fptr = fopen("file.txt", "w+");
    
    // Write data to file
    fprintf(fptr, "Hello, GFG!");
    
    // Rewind fptr to the beginning
    rewind(fptr);

    // Read data from file
    char ch;
    while ((ch = fgetc(fptr)) != EOF) {
        printf("%c", ch);
    }

    fclose(fptr);
    return 0;
}

Output
Hello, GFG!

Explanation: Initially, fprintf() writes "Hello, GFG!" to file.txt, moving the file pointer to the end of the written data. Then, rewind() resets the file pointer to the beginning, allowing fgetc() to read the file from the start, moving the pointer forward one character at a time during reading.

This article covers the syntax, uses and common examples of rewind() function in C.

Syntax of rewind()

The rewind() is a standard library function defined in <stdio.h> header file in C.

rewind(fptr);

Parameters:

  • fptr: Pointer to the file.

Return Value:

  • This function does not return any value.

Example of rewind()

C
#include <stdio.h>

int main() {

    FILE *f = fopen("example.txt", "w+");

    // Write initial data and rewind
    fprintf(f, "Hello, gfg! ");
    rewind(f);

    // Read from the start after rewind
    char file_data[101];
    if (fgets(file_data, sizeof(file_data), f) != NULL) {
        printf("Read after first rewind: %s\n", file_data);
    }

    // Write new data, then rewind again
    rewind(f);
    fprintf(f, "Hello, gfg2! ");
    rewind(f);

    // Read updated content after second rewind
    if (fgets(file_data, sizeof(file_data), f) != NULL) {
        printf("Read after second rewind: %s\n", file_data);
    }

    fclose(f);
    return 0;
}

Output
Read after rewind: Hello, gfg! 
Read after rewind: Hello, gfg2! 

rewind() vs fseek()

fseek() is another function that can be used to move the file pointer to the start. It is considered better than rewind() as rewind() does not return any value making it harder to find whether the function was successful or not. On the other hand, fseek() returns 0 when its execution is successful.


Similar Reads