【C语言】文本操作函数fseek、ftell、rewind

打印 上一主题 下一主题

主题 2139|帖子 2139|积分 6417

一、fseek 

  1. int fseek ( FILE * stream, long int offset, int origin );
复制代码
重新定位文件指针的位置,使其指向以origin为基准、偏移offset字节的位置。
成功返回0,失败返回非零值(通常为-1)。
origin有如下三种:分别是从开头、中间、结尾开始

  1. int main()
  2. {
  3.         FILE* pf = fopen("test.txt", "r");
  4.         if (pf == NULL)
  5.         {
  6.                 perror(pf);
  7.         }
  8.         else
  9.         {
  10.                 //abcdef
  11.                 int ch = fgetc(pf);
  12.                 printf("%c\n", ch);//a
  13.                 ch = fgetc(pf);
  14.                 printf("%c\n", ch);//b
  15.                 ch = fgetc(pf);
  16.                 printf("%c\n", ch);//c
  17.                 //想要跳回到b进行读取,三种方法
  18.                 //1.fseek(pf, 1, SEEK_SET);
  19.                 //2.fseek(pf, -2, SEEK_CUR);
  20.                 fseek(pf, -5, SEEK_END);
  21.                 ch = fgetc(pf);
  22.                 printf("%c\n", ch);//b
  23.         }
  24.         return 0;
  25. }
复制代码


 二、ftell

  1. long int ftell ( FILE * stream );
复制代码
得到的是返回文件指针相对于起始位置的偏移量数字的大小代表当前光标距离文件起始处的字节数。
返回值的类型是long
  1. int main()
  2. {
  3.         FILE* pf = fopen("test.txt", "r");
  4.         if (pf == NULL)
  5.         {
  6.                 perror(pf);
  7.         }
  8.         else
  9.         {
  10.                 //abcdef
  11.                 int ch = fgetc(pf);
  12.                 printf("%c\n", ch);//a
  13.                 printf("%d\n", ftell(pf));//偏移量1
  14.                 ch = fgetc(pf);
  15.                 printf("%c\n", ch);//b
  16.                 printf("%d\n", ftell(pf));//偏移量2
  17.                 ch = fgetc(pf);
  18.                 printf("%c\n", ch);//c
  19.                 printf("%d\n", ftell(pf));//偏移量3
  20.         }
  21.         return 0;
  22. }
复制代码

三、rewind 

  1. void rewind ( FILE * stream );
复制代码
使文件读写指针指向文件开始位置 
  1. int main()
  2. {
  3.         FILE* pf = fopen("test.txt", "r");
  4.         if (pf == NULL)
  5.         {
  6.                 perror(pf);
  7.         }
  8.         else
  9.         {
  10.                 //abcdef
  11.                 int ch = fgetc(pf);
  12.                 printf("%c\n", ch);//a
  13.                 ch = fgetc(pf);
  14.                 printf("%c\n", ch);//b
  15.                 ch = fgetc(pf);
  16.                 printf("%c\n", ch);//c
  17.                 rewind(pf);
  18.                 ch = fgetc(pf);
  19.                 printf("%c\n", ch);//a
  20.         }
  21.         return 0;
  22. }
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

鼠扑

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表