0
0
CHow-ToBeginner · 3 min read

How to Use rewind() Function in C: Syntax and Examples

In C, use the rewind(FILE *stream) function to set the file position indicator back to the start of the file. This allows you to reread or rewrite the file from the beginning without closing and reopening it.
📐

Syntax

The rewind function takes a single argument, which is a pointer to a FILE object. It resets the file position indicator to the beginning of the file and clears the error and EOF flags.

  • FILE *stream: The file pointer returned by fopen() or similar functions.
c
void rewind(FILE *stream);
💻

Example

This example opens a text file, reads the first line, then uses rewind() to go back to the start and read the first line again.

c
#include <stdio.h>

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

    char buffer[100];

    // Read first line
    if (fgets(buffer, sizeof(buffer), file) != NULL) {
        printf("First read: %s", buffer);
    }

    // Rewind to beginning
    rewind(file);

    // Read first line again
    if (fgets(buffer, sizeof(buffer), file) != NULL) {
        printf("After rewind: %s", buffer);
    }

    fclose(file);
    return 0;
}
Output
First read: Hello, world! After rewind: Hello, world!
⚠️

Common Pitfalls

  • Calling rewind() on a NULL or unopened file pointer causes undefined behavior.
  • rewind() does not return a value, so you cannot check for errors directly; use ferror() to check for errors after rewinding.
  • Remember that rewind() clears the EOF and error flags, so you can read the file again from the start.
c
#include <stdio.h>

int main() {
    FILE *file = NULL;

    // Wrong: calling rewind on NULL pointer
    // rewind(file); // This will cause a crash or undefined behavior

    // Correct usage:
    file = fopen("example.txt", "r");
    if (file == NULL) {
        perror("Failed to open file");
        return 1;
    }

    rewind(file); // Safe to call now

    fclose(file);
    return 0;
}
📊

Quick Reference

FunctionDescription
rewind(FILE *stream)Sets file position to the beginning and clears error/EOF flags
fseek(FILE *stream, long offset, int whence)Moves file position indicator to a specific location
ftell(FILE *stream)Returns current file position indicator
ferror(FILE *stream)Checks if an error occurred on the file stream

Key Takeaways

Use rewind() to reset a file pointer to the start of the file for rereading or rewriting.
Pass a valid FILE pointer to rewind(); calling it on NULL causes errors.
rewind() clears EOF and error flags but does not return an error code.
Use ferror() to check for errors after calling rewind().
rewind() is simpler than fseek() when you just want to go back to the file start.