Rewinding a file to the start
What you'll learn: How to move the file pointer back to the very beginning of a file so you can read its contents again without closing and reopening it.
The cassette tape analogy
Imagine you are listening to an old-school cassette tape. As you listen, the tape moves from the left spool to the right spool. When the song ends, the "play head" is sitting at the end of the music. If you want to hear that same song again, you don't throw the tape away and buy a new one; you simply hit the rewind button to spin the tape back to the beginning.
In C, your file pointer (the FILE * variable) works exactly like that play head. As you read data using functions like fgets or fscanf, the pointer advances through the file. If you reach the end of the file (EOF) and want to read it a second time, you need to "rewind" that pointer.
Using the rewind() function
C provides a straightforward function for this: rewind(). It takes one argument: the pointer to the file you want to reset.
When you call rewind(fptr), two important things happen:
- The position indicator is moved to the first byte of the file.
- The "End of File" (EOF) flag is cleared, allowing you to start reading fresh.
Code Example: Reading twice
Here is how you might read a file, reach the end, and then rewind it to read it all over again.
#include <stdio.h>
int main() {
FILE *fptr = fopen("notes.txt", "r");
char buffer[100];
if (fptr == NULL) return 1;
// First pass: Read and print everything
printf("First Read:\n");
while (fgets(buffer, 100, fptr) != NULL) {
printf("%s", buffer);
}
// At this point, fptr is at the end of the file.
// If we tried to read now, we would get nothing.
// Rewind to the start
rewind(fptr);
// Second pass: Read and print everything again
printf("\nSecond Read (after rewind):\n");
while (fgets(buffer, 100, fptr) != NULL) {
printf("%s", buffer);
}
fclose(fptr);
return 0;
}
Why not just reopen the file?
You might wonder why we don't just fclose() and fopen() the file again. While that works, it is "expensive" for the computer. Opening a file requires the operating system to find the file on the disk and set up new permissions and buffers. Rewinding is much faster because it keeps the connection open and simply moves the "cursor" back to the start.
Key takeaway
Use rewind(file_pointer); to instantly reset your position to the beginning of a file and clear any end-of-file errors.