21 - rewind()函数

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:

  1. 参数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;
}

文件内容如下图所示:

在这里插入图片描述

代码运行结果如下图所示:

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值