急急急,求帮忙我完善一个C语言的编程,,我自己已经写好其他了,还剩文件部分不会弄

具体我写的代码如图,怎样才能添加文件保存,打开功能

这个是具体要求

给你一个读文件和写文件的参考程序,自己照着修改下。按照你的要求写的工作量很大,还是你自己修改吧。文件格式不一定是.bat,可以是.txt
void readdat()
{
FILE *fp;
int i,j,m,n,s=0,temp1=0,temp2=0;
float q;
struct CLASS *t1,*t2,*t3;
struct STUD *p1,*p2,*p3;
head=NULL;
if((fp=fopen("message.dat","r"))==NULL)
{
fprintf(stderr,"error:can't create file\n");
return;
}
while(!feof(fp))
{
t3=(struct CLASS *)malloc(sizeof(struct CLASS));
if(temp1==0)
{
head=t3;
t1=head;
t1->next=NULL;
temp1++;
}
else if(temp1==1)
{
t1->next=t3;
t1=t3;
t1->next=NULL;
}
fscanf(fp,"%d%d%f",&m,&n,&q);
t1->number=m;t1->students=n;t1->average=q;
for(j=0;j<t1->students;j++)
{
p1=(struct STUD *)malloc(sizeof(struct STUD));
if(temp2==0)
{
t1->first=p1;
p1->next=NULL;
p2=p1;
temp2++;
}
else if(temp2==1)
{
p2->next=p1;
p1->next=NULL;
p2=p1;
}
fscanf(fp,"%s%s%s%s%d%s%s",&p1->number,&p1->name,&p1->sex,&p1->restudy,&p1->age,&p1->roomnum,&p1->tel);
for(i=0;i<5;i++)
fscanf(fp,"%d",&p1->score[i]);
fscanf(fp,"%f",&p1->average);
}
temp2=0;
}
fclose(fp);
}
void writedat()
{
FILE *fp;
int i;
struct CLASS *pclass;
struct STUD *pstud;
if((fp=fopen("message.dat","w"))==NULL) {
fprintf(stderr,"error:can't create file\n");
return;
}
pclass=(struct CLASS *)malloc(sizeof(struct STUD));
pclass=head;
pstud=pclass->first;
for(;pclass!=NULL;pclass=pclass->next)
{
fprintf(fp,"%d\n%d\n%f\n",pclass->number,pclass->students,pclass->average);
pstud=pclass->first;
for(;pstud!=NULL;pstud=pstud->next)
{
fprintf(fp,"%s\n%s\n%s\n%s\n%d\n%s\n%s\n",pstud->number,pstud->name,pstud->sex,pstud->restudy,pstud->age,pstud->roomnum,pstud->tel);
for(i=0;i<5;i++)
fprintf(fp,"%d\n",pstud->score[i]);
fprintf(fp,"%f\n",pstud->average);
}
}
fclose(fp);
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-05-14

我写了俩现成的函数,你直接调用就行

 

char *pFileName = "信息.dat";
// 将Person信息增加到文件中
// 返回值: 1 成功,0 失败
int writePersonToFile(Person *pPerson)
{
int ret = 0;
FILE *fp = fopen(pFileName, "ab");
if (NULL == fp)
{
printf("Open file %s error!\n", pFileName);
return ret;
}
if (1 != fwrite(pPerson, sizeof(Person), 1, fp))
{
printf("Write file %s error!\n", pFileName);
return ret;
}
fclose(fp);
return 1;
}
// 读取文件中指定位置的Person信息
// 返回值: 1 成功,0 失败
int readPersonFromFile(Person *pPerson, unsigned int pos)
{
int ret = 0;
unsigned int fileSize = 0;
FILE *fp = fopen(pFileName, "rb");
if (NULL == fp)
{
printf("Open file %s error!\n", pFileName);
return ret;
}
fseek(fp, 0, SEEK_END);
if (0 == (fileSize = ftell(fp)))
{
printf("File %s has no data!\n", pFileName);
return ret;
}
if (fileSize / sizeof(Person) <= pos)
{
printf("Data of position %d does not exist!\n");
return ret;
}
fseek(fp, pos * sizeof(Person), SEEK_SET);
if (1 != fread(pPerson, sizeof(Person), 1, fp))
{
printf("Read file %s error!\n", pFileName);
return ret;
}
fclose(fp);
return 1;
}

 

 

有问题联系我。

企鹅 287989240

相似回答