rewind() in C

The rewind() function in C resets the file pointer to the beginning of a file. It is a part of the standard input/output library and provides a simple way to reposition the file pointer without specifying an offset.

Syntax

                            
void rewind(FILE *stream);
                            
                        

Parameters

The rewind() function does not return a value and does not report any errors. It is equivalent to calling fseek(file, 0, SEEK_SET).

Example: Using rewind()

                            
#include <stdio.h>
int main() 
{
    FILE *file = fopen("example.txt", "w+");
    if (file == NULL) {
        printf("Error opening file\n");
        return 1;
    }

    // Write data to the file
    fputs("Hello, World!", file);

    // Reset the file pointer to the beginning
    rewind(file);

    // Read and print the data
    char buffer[50];
    if (fgets(buffer, sizeof(buffer), file) != NULL) {
        printf("Data: %s\n", buffer);
    }
              
    fclose(file);
    return 0;
}
                            
                        

Output:

Data: Hello, World!
                            
#include <stdio.h>
int main() 
{
    FILE *file = fopen("example.txt", "w+");
    if (file == NULL) {
        printf("Error opening file\n");
        return 1;
    }

    // Write data to the file
    fputs("Hello, World!", file);

    // Reset the file pointer to the beginning
    rewind(file);

    // Read and print the data
    char buffer[50];
    if (fgets(buffer, sizeof(buffer), file) != NULL) {
        printf("Data: %s\n", buffer);
    }
              
    fclose(file);
    return 0;
}
                            
                        

Output:

Data: Hello, World!

Key Points