top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Usage of function rewind() in C/C++?

+7 votes
624 views

What will the function rewind() do? How can we use it?

posted Jan 4, 2014 by Prachi Agarwal

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

The rewind function sets the file position indicator for the stream pointed to by stream to the beginning of the file.

Example

int main()
{
  FILE *fp = fopen("test", "r");

  if ( fp == NULL ) {
    /* Handle open error */
  }

  /* Do some processing with file*/
   ...
  rewind(fp);  /* This will set the indicator at the start of the file again */
  ...
 }

However its not safe to user rewind as there is no way to check if rewind is successful or not. In the above code, fseek() can be used instead of rewind() to see if the operation succeeded. Following lines of code can be used in place of rewind(fp);

if ( fseek(fp, 0L, SEEK_SET) != 0 ) {
  /* Handle repositioning error */
}

Credit: https://www.securecoding.cert.org/confluence/display/seccode/FIO07-C.+Prefer+fseek%28%29+to+rewind%28%29

answer Jan 4, 2014 by Salil Agrawal
Similar Questions
+4 votes

Can someone explain me the usage of function pointer? Probably with real time examples ?

+7 votes
#include<stdio.h>

int &fun()
{
   static int x;
   return x;
}   

int main()
{
   fun() = 10;
   printf(" %d ", fun());

   return 0;
}

It is fine with c++ compiler while giving error with c compiler.

0 votes

Which is the best practice for variable declaration within the function ? Or is it vary from one language to other one ?

+6 votes
...