lseek()、ftell()、rewind()、fseek()函数

lseek(FILE * stream, int offset, int whence);
fseek(FILE * stream, long offset, int whence);
两函数参数whence可选四种参数:
1. SEEK_SET 参数offset 即为新的读写位置.
2. SEEK_CUR 以目前的读写位置往后增加offset 个位移量.
3. SEEK_END 将读写位置指向文件尾后再增加offset 个位移量.
4. 当whence 值为SEEK_CUR 或SEEK_END 时, 参数offet 允许负值的出现.

lseek()返回值:当调用成功时则返回目前的读写位置, 也就是距离文件开头多少个字节. 若有错误则返回-1;
fseek()返回值:当调用成功时则返回0, 若有错误则返回-1, errno 会存放错误代码.

long ftell(FILE * stream);
函数说明 ftell()用来取得文件流目前的读写位置。参数stream为已打开的文件指针

void rewind(FILE * stream);
函数说明 rewind()用来把文件流的读写位置移至文件开头。

int fstat(int fildes,struct stat *buf);
函数说明 fstat()用来将参数fildes所指的文件状态,复制到参数buf所指的结构中(struct stat)。

#include <stdio.h>
#include<stdlib.h>

int main()
{
  FILE * stream;
  long offset;
  
  char a;
  fpos_t pos;
  

	if ((stream = fopen("D:\\Users\\ASUS\\Desktop\\asd.txt", "rb"))==NULL)
	{
	    printf("%s\n","can not open file\n");
	    exit(0);
	} 

  fseek(stream, 5, SEEK_SET);
  printf("ftell the current offset = %d\n", ftell(stream));
    
  rewind(stream);
  fgetpos(stream, &pos);
  printf("after rewind , offset = %d\n", pos);
 
 //打印首字符 
   a = fgetc(stream);
   printf("%c\n", a);
     
  pos = 10;
  fsetpos(stream, &pos);//设置指针位置为pos 
  printf("offset = %d\n", ftell(stream));
  fclose(stream);   //关闭指针 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值