C语言,.dat文件储存
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
struct shop
{
long date;
int buy_money;
int money;
char style[10];
int time;
char place[50];
};
struct student
{
long end_date;
long money;
char sta;
int time;
char g_sta;
char d_sta;
int help_money;
char place[50];
};
int shopping(long date,int buy_money,char * style,char *place)
{
FILE *fp,*fstudent;
struct shop *a;
struct student *stu;
a=(struct shop *)malloc(sizeof(struct shop));
stu=(struct student *)malloc(sizeof(struct student));
a->date=date;
a->buy_money=buy_money;
strcpy(a->style,style);
strcpy(a->place,place);
if((fstudent=fopen("student.dat","rb+"))==NULL)
{
printf("cannot open file student\n");
return;
}
if(fread(stu,sizeof(struct student),1,fstudent)!=1)
{
printf("file read error!");
}
if(stu->money<buy_money) return -1;
if(stu->g_sta=='Y') return 0;
stu->time++;
a->time=stu->time;
stu->money-=buy_money;
fclose(fstudent);
fstudent=fopen("student.dat","wb+");
fwrite(stu,sizeof(struct student),1,fstudent);
free(stu);
fclose(fstudent);
if((fp=fopen("shop.dat","ab"))==NULL)
{
printf("cannot open file shop\n");
return;
}
if(fwrite(a,sizeof(struct shop),1,fp)!=1)
printf("file write error\n");
fclose(fp);
}
int main()
{
long date=20130506;
int buy_money=20;
char *style="abcd";
char *place="abcd";
shopping(date,buy_money, style,place);
return;
}
就是想同时联系两个文件,让shopping发生时shop.dat文件中的time等于student.dat的time+1;同时student的time也加一.