您的位置:首页 > 编程语言 > C语言/C++

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

2017-08-14 19:35 162 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: