顺序读写函数练习使用

本文详细介绍了C语言中顺序读写文件的四个函数:fputc/fgetc用于单字符操作,fputs/fgets处理字符串,fprintf/fscanf用于结构体格式化输入/输出,以及fwrite/fread用于二进制数据传输。通过实例展示了如何在主函数中使用这些函数进行文件操作。
摘要由CSDN通过智能技术生成

顺序读写函数练习使用

代码如下:

1.fputc和fgetc的练习使用

int main()
{
	FILE* pr = fopen("date1.txt", "w");//在文件date1中写入数据
	if (pr == NULL)
	{
		return 1;
	}
	fputc('b', pr);//fputc
	fclose(pr);
	pr = NULL;

	FILE* ppr = fopen("date1.txt", "r");//在文件date1中调用数据
	if (ppr == NULL)
	{
		return 1;
	}
	char n = fgetc(ppr);
	printf("读取出来的字符为%c", n);
	fclose(ppr);
	ppr = NULL;

	return 0;
}

2.fputs和fgets的练习使用

int main()
{
	FILE* pr = fopen("date2.txt", "w");//在文件date2中写入数据
	if (pr == NULL)
	{
		return 1;
	}
	fputs("hello world", pr);
	fclose(pr);
	pr = NULL;

	FILE* ppr = fopen("date2.txt", "r");//在文件date2中调用数据
	if (ppr == NULL)
	{
		return 1;
	}
	char arr[20] = { 0 };
	fgets(arr, 10, ppr);
	printf("%s", arr);
	fclose(ppr);
	ppr = NULL;

	return 0;
}

3.fprintf和fscanf的练习使用

struct Stu
{
	char name[20];
	int age;
	float score;
};

int main()
{
	struct Stu s = { "lisi", 20, 90.3f };
	struct Stu x = { 0 };
	FILE*pf = fopen("data.txt", "w");//在文件date3中写入数据
	if (pf == NULL)
	{
		return 1;
	}
	fprintf(pf, "%s %d %.1f", s.name, s.age, s.score);

	fclose(pf);
	pf = NULL;

	FILE* pff = fopen("data.txt", "r");//在文件date3中调用数据
	if (pff == NULL)
	{
		return 1;
	}	
	fscanf(pff, "%s %d %f", x.name, &(x.age), &(x.score));
	fprintf(stdout, "%s %d %.1f\n", x.name, x.age, x.score);

	fclose(pff);
	pff = NULL;

	return 0;
}

4.fread和fwrite的练习使用

struct people
{
	char name[20];
	int age;
	float score;
};

int main()
{
	struct people x = { "lisi",20,65.3f };
	struct people z = { 0 };
	FILE* pr = fopen("date4.txt", "wb");
	if (pr == NULL)
	{
		return 1;
	}
	fwrite(&x, sizeof(x), 1, pr);

	fclose(pr);
	pr = NULL;


	FILE* prr = fopen("date4.txt", "rb");
	if (prr == NULL)
	{
		return 1;
	}
	fread(&z, sizeof(z), 1, prr);
	fprintf(stdout, "%s %d %.1f\n", z.name, z.age, z.score);

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值