Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ <cstdio> 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 below example, 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 <cstdio>
 
int main (){

  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
  while(!feof(pFile)) {
    c = getc(pFile);
    putchar(c); 
  }

  //close the file
  fclose (pFile);

  return 0;
}

The output of the above code will be:

Hello World!.

❮ C++ <cstdio> Library

5