一些文件操作函数

1.fseek的用法:
fseek函数的原型是int fseek(FILE*stream,long offset,int fromwhere);函数设置文件指针stream的位置.如果执行成功,stream将以fromwhere为基准,偏移offset个字节的位置,offset为正数向右偏移,为负数向左偏移.

int main()
{
	FILE* ps = fopen("test.txt", "r");
	int ch = fgetc(ps);
	printf("%c ", ch);
	ch = fgetc(ps);
	printf("%c ", ch);
	fseek(ps, 2, SEEK_CUR);
	ch=getc(ps);
	printf("%c ", ch);
}

在这里插入图片描述
2.ftell的用法:
ftell函数原型为long int ftell(FILE*stream),用于获取文件位置指针当前位置相对于文件首的偏移字节数.

nt main()
{
	FILE* ps = fopen("test.txt", "r");
	int ch = fgetc(ps);
	printf("%c ", ch);
	ch = fgetc(ps);
	printf("%c ", ch);
	fseek(ps, 2, SEEK_CUR);
	ch=getc(ps);
	printf("%c ", ch);
	int ret = ftell(ps);
	printf("%d ", ret);

}
```![在这里插入图片描述](https://img-blog.csdnimg.cn/464d9ddafc2345f4854e648002ef6854.png)
3.rewind的用法:函数原型void rewind(FILE*filepointer),将读写位置指针重制到文件开头.

int main()
{
FILE* ps = fopen(“test.txt”, “r”);
int ch = fgetc(ps);
printf("%c “, ch);
ch = fgetc(ps);
printf(”%c “, ch);
fseek(ps, 2, SEEK_CUR);
ch=getc(ps);
printf(”%c “, ch);
int ret = ftell(ps);
printf(”%d “, ret);
rewind(ps);
ch = fgetc(ps);
printf(”%c ", ch);

}


![在这里插入图片描述](https://img-blog.csdnimg.cn/9ef7d626aa4547e79be4cc09f848bd43.png)
4.ferror和feof函数
feof:当文件读取结束时,判断是不是遇到文件末尾才结束的.如果没有到文件末尾,返回0,到了文件末尾,返回非0,

int main()
{
FILE* ps = fopen(“test.txt”, “r”);
int ch = fgetc(ps);
printf(“%c “, ch);
ch = fgetc(ps);
printf(”%c “, ch);
fseek(ps, 2, SEEK_CUR);
ch=getc(ps);
printf(”%c “, ch);
int ret = ftell(ps);
printf(”%d “, ret);
rewind(ps);
ch = fgetc(ps);
printf(”%c\n”, ch);
if (feof(ps))
{
printf(“到了文件末尾\n”);
}
else
{
printf(“没到文件末尾\n”);
}

}

ferror:判断函数是否是遇到错误才读取结束的,如果是,则返回非0,否则返回1.

int main()
{
FILE* ps = fopen(“test.txt”, “r”);
int ch = fgetc(ps);
printf(“%c “, ch);
ch = fgetc(ps);
printf(”%c “, ch);
fseek(ps, 2, SEEK_CUR);
ch=getc(ps);
printf(”%c “, ch);
int ret = ftell(ps);
printf(”%d “, ret);
rewind(ps);
ch = fgetc(ps);
printf(”%c\n”, ch);
if (ferror(ps))
{
printf(“遇到错误\n”);
}
else
{
printf(“没遇到错误\n”);
}

}

![在这里插入图片描述](https://img-blog.csdnimg.cn/03c31146beac4e86adce4ba5d2a6979a.png)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值