C语言——文件的随机读写

目录

1.fseek函数

        1.1原型:

        1.2使用:

2.ftell函数

        2.1原型

        2.1使用

3.rewind函数

        3.1原型

        3.2使用


1.fseek函数

        根据文件指针的位置和偏移量来定位文件指针。

        1.1原型:

 

fseek函数是根据文件指针位置和偏移量来定位文件指针。

FILE *stream:是要操作的文件指针

long offset:是文件指针的偏移量

int origin:  是起始位置,是指文件指针从哪个位置开始的偏移量。

它有三种形参,分别是:SEEK_CUR(文件指针当前位置开始),SEEK_END(文件指针末尾位置开始),SEEK_SET(文件起始位置开始)。如下:

        1.2使用:

#include<errno.h>
#include<string.h>
#include<stdio.h>
int main()
{
	FILE* pf = fopen("text.txt", "r");
	if (NULL == pf)
	{
		strerror(errno);
		return 1;
	}
	//写文件
	fseek(pf, 2, SEEK_SET);//以文件起始位置开始,向后偏移2Byte
	int c = fgetc(pf);
	printf("%c", c);
	fseek(pf, 2, SEEK_CUR);//以文件指针当前位置开始,向后偏移2Byte
	 c = fgetc(pf);
	printf("%c", c);
	fseek(pf, -3, SEEK_END);//以文件末尾开始向前偏移3个byte
	 c = fgetc(pf);
	printf("%c", c);
	fclose(pf);//关闭文件
	pf = NULL;
}

2.ftell函数

        返回文件指针相对于起始位置的偏移量。

        2.1原型

 

        2.1使用

#include<errno.h>
#include<string.h>
#include<stdio.h>
int main()
{
	FILE* pf = fopen("text.txt", "r");
	if (NULL == pf)
	{
		strerror(errno);
		return 1;
	}
	//写文件
	fseek(pf, 2, SEEK_SET);//以文件起始位置开始,向后偏移2Byte
	int c = fgetc(pf);
	printf("%c\n", c);
	fseek(pf, 2, SEEK_CUR);//以文件指针当前位置开始,向后偏移2Byte
	 c = fgetc(pf);
	printf("%c\n", c);
	fseek(pf, -3, SEEK_END);//以文件末尾开始向前偏移3个byte
	 c = fgetc(pf);
	printf("%c\n", c);
	printf("%d\n", ftell(pf));//返回文件指针相对于起始位置的偏移量
	fclose(pf);//关闭文件
	pf = NULL;
}

3.rewind函数

        让文件指针的位置回到文件的起始位置。 

        3.1原型

 

        3.2使用

#include<errno.h>
#include<string.h>
#include<stdio.h>
int main()
{
	FILE* pf = fopen("text.txt", "r");
	if (NULL == pf)
	{
		strerror(errno);
		return 1;
	}
	//写文件
	fseek(pf, 2, SEEK_SET);//以文件起始位置开始,向后偏移2Byte
	int c = fgetc(pf);
	printf("%c\n", c);
	fseek(pf, 2, SEEK_CUR);//以文件指针当前位置开始,向后偏移2Byte
	 c = fgetc(pf);
	printf("%c\n", c);
	fseek(pf, -3, SEEK_END);//以文件末尾开始向前偏移3个byte
	 c = fgetc(pf);
	printf("%c\n", c);
	printf("%d\n", ftell(pf));//返回文件指针相对于起始位置的偏移量
	rewind(pf);//让文件指针回到文件的起始位置
	c=fgetc(pf);
	printf("%c", c);
	fclose(pf);//关闭文件
	pf = NULL;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值