C Standard Library

C <stdio.h> - rewind() Function



The C <stdio.h> rewind() function sets the file position indicator to the beginning of the given file stream.

A call to this function undoes the effects of ungetc() function and clears the end-of-file state, if it is set.

On streams open for update (read+write), a call to rewind() allows to switch between reading and writing. If a read or write error occurs, the error indicator ferror() for the stream is set.

Syntax

void rewind ( FILE * stream );

Parameters

stream Specify a pointer to a FILE object that identifies the stream.

Return Value

None.

Example:

In the example below, program creates an empty file for output operations if the file test.txt does not exist. If the file already exists, its contents are discarded and the file is treated as a new empty file.

The C string "Hello World!." is written to it using fputs() function. Then the position of the file is set to start using rewind() function to display the content of the file.

#include <stdio.h>
 
int main (){
  //open the file in write and read mode
  FILE * pFile = fopen("test.txt","w+");
  int c;

  //writes "Hello World!." to 
  //the file stream
  fputs("Hello World!.", pFile);

  //set the position to the start
  rewind(pFile);

  //display the content of the file
  c = getc(pFile);
  while(c != EOF) {
    putchar(c);
    c = getc(pFile);
  }

  //close the file
  fclose (pFile);

  return 0;
}

The output of the above code will be:

Hello World!.

❮ C <stdio.h> Library