C语言-文件读写回顾.上

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

//fputc fgetc
void test01() {
	
	{
		FILE* f_write = fopen("./test01.txt", "w+");
		if (f_write == NULL) {
			return;
		}
		char buf[] = "this is first test";
		for (int i = 0; i < strlen(buf); ++i) {
			//第一个参数:要写入的字符 第二个参数:文件指针
			fputc(buf[i], f_write);
		}
		fclose(f_write);
	}
	{
		FILE* f_read = fopen("./test01.txt", "r");
		if (f_read == NULL) {
			return;
		}
		char ch;
		//第一个参数:文件指针
		while ((ch = fgetc(f_read)) != EOF/*EOF End Of File*/) {
			printf("%c",ch);
		}
		fclose(f_read);
	}
}

//fputs fgets
void test02() {
	{
		FILE* f_write = fopen("./test02.txt", "w+");
		if (f_write == NULL) {
			return;
		}
		char* buf[] = {
			"11111111\n",
			"22222222\n",
			"33333333\n",
			"44444444\n"
		};
		for (int i = 0; i < sizeof(buf) / sizeof(buf[0]); ++i) {
			//第一个参数:要写入的字符串 第二个参数:文件指针
			fputs(buf[i], f_write);
		}
		fclose(f_write);
	}
	{
		FILE* f_read = fopen("./test02.txt", "r");
		if (f_read == NULL) {
			return;
		}
		char ch;
		//EOF End Of File
		while (!feof(f_read)) {
			char buf[1024] = { 0 };
			//第一个参数:目标缓冲区 第二个参数:缓冲区大小 第三个参数:文件指针
			fgets(buf, 1024, f_read);
			printf("%s",buf);
		}
		fclose(f_read);
	}
}
struct Hero
{
	char name[64];
	int age;
};
//fwrite fread
void test03() {
	{
		FILE* f_write = fopen("./test03.txt", "wb");
		if (f_write == NULL) {
			return;
		}
		struct Hero heros[] =
		{
			{"张三",18},
			{"李四",20},
			{"王五",33},
			{"赵六",54}
		};
		for (int i = 0; i < sizeof(heros)/sizeof(heros[0]); ++i) {
			//第一个参数:数据地址 第二个参数:块大小 第三个参数:块个数 第四个参数:文件指针
			fwrite(&heros[i], sizeof(struct Hero), 1, f_write);
		}
		fclose(f_write);
	}
	{
		FILE* f_read = fopen("./test03.txt", "rb");
		if (f_read == NULL) {
			return;
		}
		struct Hero temp[4];
		//第一个参数:数据地址 第二个参数:块大小 第三个参数:块个数 第四个参数:文件指针
		fread(&temp, sizeof(struct Hero), 4, f_read);

		for (int i = 0; i < sizeof(temp) / sizeof(temp[0]); ++i) {
			printf("name:%s age:%d\n",temp[i].name,temp[i].age);
		}
		fclose(f_read);
	}
}
int main(int argc, char* argv[])
{
	//test01();
	//test02();
	//test03();
	system("pause");
	return EXIT_SUCCESS;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值