1 函数原型
rewind():将指定流stream的文件位置指示符重置到文件开头,函数原型如下:
void rewind(FILE *stream);
cstdio库描述如下:
Set position of stream to the beginning
1. Sets the position indicator associated with stream to the beginning of the file.
2. The end-of-file and error internal indicators associated to the stream are cleared after a successful call to this function, and all effects from previous calls to ungetc on this stream are dropped.
3. On streams open for update (read+write), a call to rewind allows to switch between reading and writing.
注意 rewind()函数会清除文件流的文件结束指示符和错误指示符。
2 参数
rewind()函数只有一个参数stream:
- 参数stream是rewind()函数要重置的流,类型为FILE*;stream主要是文件流,就是fopen()函数的返回值。
注意 有些文章提到,使用rewind(stdin)来替代fflush(stdin)来达到类似“清空stdin输入缓冲区”的效果,该用法不推荐。
cstdio库描述如下:
stream
1. Pointer to a FILE object that identifies the stream.
3 返回值
rewind()函数的返回值类型为void。
4 示例
示例代码如下所示:
int main()
{
//
FILE* fp = NULL;
char buffer[80] = { 0 };
//
fp = fopen("1.txt", "rb");
if (fp == NULL) {
perror("Failed to open file ");
exit(1);
}
//
printf("打开文件\n");
printf("文件位置指示符当前值:%ld\n", ftell(fp));
printf("\n");
//
printf("读文件并打印\n");
fgets(buffer, 80, fp);
printf("%s\n", buffer);
printf("文件位置指示符当前值:%ld\n", ftell(fp));
printf("\n");
//
printf("移动文件读写指针至文件开头\n");
rewind(fp);
printf("文件位置指示符当前值:%ld\n", ftell(fp));
printf("\n");
//
fclose(fp);
//
return 0;
}
文件内容如下图所示:
代码运行结果如下图所示: