fseek () против rewind () в C

Опубликовано: 17 Февраля, 2022

В C предпочтительнее использовать fseek () перед 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

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

за исключением того, что индикатор ошибки для потока также очищается.

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.

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

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 */
}

Источник: https://www.securecoding.cert.org/confluence/display/seccode/FIO07-C.+Prefer+fseek%28%29+to+rewind%28%29

Эта статья предоставлена Рахулом Гуптой . Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше.

Хотите узнать о лучших видео и практических задачах, ознакомьтесь с Базовым курсом C для базового и продвинутого C.