C 語言 文件寫入 塊處理

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

/*
	高級保存選項 -  編碼  - unicode(utf-8 帶簽名)-65001 
	這樣設置事後, 在命令行輸出的中文不會亂碼.
*/
struct Hero
{
	char name[64];
	int age;
};

void write_block(FILE* fd, struct Hero (*p)[4],int size, int len)
{

	for (int i=0;i < len;i++ )
	{
		fwrite(&(*p)[i], size, 1, fd);
	}
}


void read_block(FILE* fd, struct Hero(*buf)[4],int size ,int len )
{
	fread(&(*buf), size, len, fd);
}

void test()
{

	struct Hero node[4] = {
		{"張三",11},
		{"李四",12},
		{"王五",13},
		{"馬六", 14}
	};

	FILE* f_write = fopen("./hero.txt", "wb");
	write_block(f_write, &node,sizeof(struct Hero),4);
	fclose(f_write);



	struct Hero hers[4];
	FILE* f_read = fopen("./hero.txt", "rb");
	read_block(f_read, &hers,  sizeof(struct Hero), 4);

	fclose(f_read);

	for (int i=0;i < 4;i++)
	{
		printf("name:%s,age:%d\n", hers[i].name, hers[i].age);
	}	
}

int main()
{
	test();
	return 0;
}
相關文章
相關標籤/搜索