【C语言进阶】文件操作(二)

1、文件随机读写

1.1、fseek函数

fseek函数的作用,根据文件指针的位置和偏移量来定位文件指针

随机读文件

#include <stdio.h>
#include <errno.h>
#include <string.h>

int main()
{
	FILE* pf = fopen("text.txt", "r");
	if (pf == NULL)
	{
		printf("%s\n", strerror(errno));
	}
	//读文件
	int ch = fgetc(pf);
	printf("%c\n", ch);
	ch = fgetc(pf);
	printf("%c\n", ch);
	//定位文件指针
	//fseek(pf, 1, SEEK_CUR);//三个参数(流、偏移量、文件指针位置)
	//fseek(pf, 3, SEEK_SET);
	fseek(pf, -1, SEEK_END);
	ch = fgetc(pf);
	printf("%c\n", ch);

	fclose(pf);
	pf = NULL;

	return 0;
}

随机写文件

#include <stdio.h>
#include <errno.h>
#include <string.h>

int main()
{
	FILE* pf = fopen("text.txt", "w");
	if (pf == NULL)
	{
		printf("%s\n", strerror(errno));
	}
	//写文件
	int ch = 0;
	for (ch = 'a'; ch <= 'z'; ch++)
	{
		fputc(ch, pf);
	}
	//定位文件指针
	fseek(pf, -1, SEEK_END);//可以在指定位置修改你写入的内容
	fputc('#', pf);

	fclose(pf);
	pf = NULL;

	return 0;
}

1.2、ftell函数

ftell函数的作用是告诉你当前文件指针的偏移量(告诉你当前文件指针位置)

#include <stdio.h>
#include <errno.h>
#include <string.h>

int main()
{
	FILE* pf = fopen("text.txt", "r");
	if (pf == NULL)
	{
		printf("%s\n", strerror(errno));
	}
	//读文件
	int ch = fgetc(pf);
	printf("%c\n", ch);
	ch = fgetc(pf);
	printf("%c\n", ch);

	int ret = ftell(pf);
	printf("%d\n", ret);

	fclose(pf);
	pf = NULL;
	return 0;
}

1.3、rewind函数

rewind函数的作用是把文件指针偏移量置为 0,文件指针重新指向文件开头

#include <stdio.h>
#include <errno.h>
#include <string.h>

int main()
{
	FILE* pf = fopen("text.txt", "r");
	if (pf == NULL)
	{
		printf("%s\n", strerror(errno));
	}
	//读文件
	int ch = fgetc(pf);
	printf("%c\n", ch);
	ch = fgetc(pf);
	printf("%c\n", ch);

	int ret = ftell(pf);
	printf("%d\n", ret);

	rewind(pf);
	ret = ftell(pf);
	printf("%d\n", ret);

	fclose(pf);
	pf = NULL;
	return 0;
}

2、判断文件读取是否结束

1、文本文件读取是否结束
判断返回值是否为EOF(fgetc)或者NULL(fgets)

例如:
fgetc判断是否为EOF;
fgets判断返回值是否为NULL;

2、二进制文件读取结束判断,判断返回值是否小于实际要读取的个数

例如:
fread判断返回值是否小于实际要读的个数

3、文件缓冲区

文件在储存的时候,会先将数据储存在缓冲区中,缓冲区存满之后,一次性写入文件中

文件读出数据时也是一样,会先将数据储存在缓冲区中,缓冲区存满之后,一次性读出来

只要你关闭文件,就会刷新缓冲区

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值