Course contentsShow
← C
Lesson 737 of 1,21910. Input and OutputFree lesson

Resetting with rewind

Resetting with rewind

What you'll learn: How to instantly move your "reading cursor" back to the very beginning of a file.

The cassette tape analogy

Imagine you are listening to an old-school cassette tape or watching a VHS movie. As you play the tape, the magnetic ribbon moves from one spool to the other. If you stop halfway through and want to hear the first song again, you can't just press "play"—you are stuck in the middle. You have to physically wind the ribbon back to the start.

In C, files work the same way. When you read 100 bytes from a file, your position (the "cursor") stays at byte 101. If you try to read again, you’ll continue toward the end. To start over from the top without closing and reopening the file, you use the rewind() function.

How rewind works

The rewind() function is part of the <stdio.h> library. It takes one argument: the pointer to the file you want to reset.

When you call rewind(filePointer), two things happen:

  1. The file position indicator is moved to the very first byte of the file.
  2. The "End-of-File" (EOF) flag is cleared, meaning if you had previously reached the end of the file, the program "forgets" it was at the end and prepares to read fresh data.

Code example: Reading twice

In this example, we read the first character of a file, reset our position, and read it again.

#include <stdio.h>

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

    if (fptr == NULL) return 1;

    // Read the first character
    letter = fgetc(fptr);
    printf("First read: %c\n", letter);

    // Reset the "tape" to the beginning
    rewind(fptr);

    // Read the first character again
    letter = fgetc(fptr);
    printf("Second read (after rewind): %c\n", letter);

    fclose(fptr);
    return 0;
}

Why use it?

You might use rewind() if you need to perform two passes on the same data. For instance, you might read a file once to count how many lines it has, rewind() to the start, and then read it a second time to actually process the content now that you know the size. It is a simple, clean way to start over without the overhead of closing and re-opening the file.

Key takeaway

Use rewind(filePointer); to instantly jump back to the beginning of a file and clear any end-of-file indicators.