c语言对结构体的读取与写入

#include <stdio.h>

#define SAVE_PATH "./student.data"


typedef struct student
{
	char name[10];
	int id;
	char addr[20];
}student;



void write_msg(const student* s,int len)
{

#define _BIN_WR

	FILE* fp;
	int i = 0;	
#ifdef _BIN_WR

	fp = fopen(SAVE_PATH,"rb+");
	if(NULL == fp)
	{
		fp = fopen(SAVE_PATH,"wb+");
	}

	fseek(fp,0,SEEK_END);

	while(i<len)
	{
		fwrite(s+i,sizeof(student),1,fp);
		i++;
	}
#else
	fp = fopen(SAVE_PATH,"r+");
	if(NULL == fp)
	{
		fp = fopen(SAVE_PATH,"w+");
	}

	fseek(fp,0,SEEK_END);
	while(i<len)
	{
		fprintf(fp,"%-7s%-3d%-7s\n",(s+i)->name,(s+i)->id,(s+i)->addr);
		i++;
	}
#endif
	fclose(fp);
}

void read()
{
	FILE* fp;
	student s;
	
#ifdef _BIN_WR	
	fp =fopen(SAVE_PATH,"rb");
	
	if(NULL == fp)
	{
		perror("open fail");
		return;
	}
	
	while(1==fread(&s,sizeof(student),1,fp))
	{
		printf("%s %d %s\n",s.name,s.id,s.addr);
	}	

#else

	fp = fopen(SAVE_PATH,"r");
	if(NULL == fp)
	{
		perror("open fail");	
	}

	while(!feof(fp))
	{
		fscanf(fp,"%s %d %s\n",s.name,&s.id,s.addr);
		printf("%s %d %s\n",s.name,s.id,s.addr);
	}



#endif

	fclose(fp);

}





int main()
{

	student s[2]={{"ylk",111,"wuhan"},{"ylk2",222,"wuhan"}};
	write_msg(s,2);
	read();
	return 0;
}
















评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值