C rewind() Function Tutorial

In this section, we will learn what the rewind() function is and how it works in C.

C rewind() Function

When a program opens a file via the call to the `fopen()` function, a position indicator to the content of the file will be also assigned.

From there, any attempt to read the content of the file via calling `fgets` or `fscanf` or `getc` function will cause the position-indicator to advance and points to the next element of that file.

But there are times that we might want to start from the beginning of the file and read from there.

This is where we can call the `rewind()` function and it will reset this position-indicator to point to the first element of the target file.

(When we say element, we mean the very content of that file! For example, if the file has characters, then the word element means the character of that file. Or if the file has binary content, the word element means each binary code in that file).

Note: the prototype of this function exists in the `stdio.h` header file and so we need to include the file in order to work with this function.

C rewind() Function Syntax:

Here’s the prototype of the function:

void rewind(FILE *stream)

C rewind() Function Parameters

This function takes only one argument and that is the address of the memory space allocated to the FILE-structure of the target file.

Note: we get this address from the call to the `fopen()` function.

C rewind() Function Return Value

The function does not return a value.

Example: using rewind() function in C

#include <stdio.h>
#include <stdlib.h>

int main() {

    //Call the the fopen function in order to open the file in read mode.
    FILE *file = fopen("G:/fileOne.txt","r");
    //if there was a problem on opening the file, exit the program.
    if (file == NULL){
        printf("Could not open the file");
        exit(EXIT_FAILURE);

    }

    char c;
    while((c = getc(file))!=EOF){
        fprintf(stdout, "%c",c);
    }
    //Rewind the position-indicator to point to the first element of the target file
    rewind(file);
    while((c = getc(file))!=EOF){
        fprintf(stdout, "%c",c);
    }
    fclose(file);


    printf("\nDone\n");
    return 0;
}

Output:

Hello,

My name is John DoeHello,

My name is John Doe

Done
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies