REWIND()

This function is used to reset the file position indicator to the beginning of a file that was previously opened using fopen(). It allows devs to start reading or writing from the start of the file again, without having to close and reopen it.

void rewind(FILE *stream);

 * Sets the file position to the beginning (0 offset)
 * Also clears the error and EOF indicators on the file stream
 * Does not check for errors — use fseek(fp, 0, SEEK_SET) + clearerr(fp) if 
   more control and error checking is required.
#include <stdio.h>

int main() {
    FILE *fp = fopen("example.txt", "r");
    if (fp == NULL) {
        perror("Failed to open file");
        return 1;
    }

    char ch;

    // Read and print first 10 characters
    for (int i = 0; i < 10 && (ch = fgetc(fp)) != EOF; i++) {
        putchar(ch);
    }

    // Reset file position to the beginning
    rewind(fp);

    printf("\nAfter rewind:\n");

    // Read and print first 10 characters again
    for (int i = 0; i < 10 && (ch = fgetc(fp)) != EOF; i++) {
        putchar(ch);
    }

    fclose(fp);
    return 0;
}

Last updated