fseek() vs rewind() in C

In C, fseek() should be preferred over rewind().

Note the following text C99 standard:
The rewind function sets the file position indicator for the stream pointed to by stream to the beginning of the file. It is equivalent to

filter_none

edit
close

play_arrow

link
brightness_4
code

(void)fseek(stream, 0L, SEEK_SET)

chevron_right


except that the error indicator for the stream is also cleared.

This following code example sets the file position indicator of an input stream back to the beginning using rewind(). But there is no way to check whether the rewind() was successful.

filter_none

edit
close

play_arrow

link
brightness_4
code

int main()
{
  FILE *fp = fopen("test.txt", "r");
  
  if ( fp == NULL ) {
    /* Handle open error */
  }
  
  /* Do some processing with file*/
  
  rewind(fp);  /* no way to check if rewind is successful */
  
  /* Do some more precessing with file */
  
  return 0;
}

chevron_right


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);

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

This article is contributed by Rahul Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


5


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.