C语言rewind()函数:将文件指针重新指向文件开头

头文件:#include <stdio.h>,rewind()函数用于,

  • 将文件内部的位置指针重新指向文件的开头
  • 同时清除和文件流相关的错误和eof标记
  • 相当于调用fseek(stream, 0, SEEK_SET)

其原型如下:

   void rewind(FILE * stream); 

【参数】stream为已打开文件的指针

文件指针FILE *stream中,包含一个读写位置指针char *_nextc,它指向下一次文件读写的位置。其结构如下:

typedef struct
{
int _fd; // 文件号
int _cleft; // 缓冲区中剩下的字节数
int _mode; // 文件操作模式
char * _nextc; // 下一个字节的位置
char * _buff; // 文件缓冲区位置
}FILE;
  • 每当进行一次读写后,该指针自动指向下一次读写的位置
  • 当文件刚打开或创建时,该指针指向文件的开始位置
  • 可以用函数ftell()获得当前的位置指针,也可以用rewind()/fseek()函数改变位置指针,使其指向需要读写的位置

【实例】读取文件的数据后再回到开头重新读取。

#include<stdio.h>
int main()
{
    FILE* stream;
    int l;
    float fp;
    char s[81];
    char c;
    stream = fopen("fscanf.txt","w+");
    if(stream == NULL)/*打开文件失败*/
    {
        printf("the file is opeaned error!\n");
    }
    else/*成功则输出信息*/
    {
        fprintf(stream,"%s %d %f %c","a_string",9,3.5,'x');
        fseek(stream,0L,SEEK_SET); /*定位文件读写指针*/
        fscanf(stream,"%s",s);
        printf("%ld\n",ftell(stream));
        fscanf(stream,"%d",&l);
        printf("%ld\n",ftell(stream));
        fscanf(stream,"%f",&fp);
        printf("%ld\n",ftell(stream));
        fscanf(stream," %c",&c);
        printf("%ld\n",ftell(stream));
        rewind(stream);/*指向文件开头*/
        fscanf(stream,"%s",s);
        printf("%s\n",s);
        fclose(stream);/*关闭流*/
    }
}

(个人:从上面的打印结果,可以推理以前的猜测是对的,fprintf实际保存到文件中的是作为字符在内存中的01序列,这也符合打印的意思) 

又如,把一个文件的内容显示在屏幕上,并同时复制到另一个文件。

#include <stdio.h>
void main()
{
FILE *fp1, *fp2;
fp1 = fopen("file1.c", "r"); // 源文件
fp2 = fopen("file2.c", "w"); // 复制到file2.c
while(!feof(fp1)) putchar(fgetc(fp1)); // 显示到屏幕上
rewind(fp1); // fp回到开始位置
while(!feof(fp1)) fputc(fgetc(fp1), fp2);
fclose(fp1);
fclose(fp2);
}

posted on 2022-05-17 12:25  朴素贝叶斯  阅读(982)  评论(0编辑  收藏  举报

导航