为什么在文件里存好的内容在经过这个函数之后就变得乱七八糟了呢?
void amend() //学生信息修改{
FILE *fp;
char a[20];
struct Student *p1,*p2,*p,*head;
struct Student stu;
int n,i,j,m=0;
if((fp=fopen("student_list.txt","r"))==NULL)
{
printf("cannot open file");
exit(0);
}
printf("Please enter the student's ID:");
scanf("%d",&n);
printf("Which one do you want to amend? Please choose the number:\n");
printf("1:name 2:sex 3:ID 4:academy 5:clas\n");
scanf("%d",&i);
head=NULL;
p1=p2=(struct Student*)malloc(sizeof(struct Student)); //开辟新单元
while(!feof(fp)) //如果没有遇见文件的结束标志
{
fscanf(fp,"%s",&p1->name); //从磁盘文件读入
fscanf(fp,"%s",&p1->sex);
fscanf(fp,"%d",&p1->ID);
fscanf(fp,"%s",&p1->academy);
fscanf(fp,"%s",&p1->clas);
m++;
if(m==1)head=p1;
else p2->next=p1;
p2=p1;
p1=(struct Student*)malloc(sizeof(struct Student));
}
p2->next=NULL;
free(p1);
fclose(fp);
p=head;
while(p!=NULL)
{
if(n==p->ID)
switch(i)
{
case 1:
printf("Please enter the new name:");
scanf("%s",a);
strcpy(p->name,a); //利用复制函数来修改姓名
break;
case 2:
printf("please enter the new sex:");
scanf("%s",a);
strcpy(p->sex,a);
break;
case 3:
printf("Please enter the new ID:");
scanf("%d",&j);
p->ID=j;
break;
case 4:
printf("Please enter the new academy:");
scanf("%s",a);
strcpy(p->academy,a);
break;
case 5:printf("Please enter the new clas:");
scanf("%s",a);
strcpy(p->clas,a);
break;
}
p=p->next;
}
fp=fopen("student_list.txt","w");
p=head;
while(p!=NULL)
{
fprintf(fp,"%s\n%s\n%d\n%s\n%s\n",stu.name,stu.sex,stu.ID,stu.academy,stu.clas);
p=p->next;
}
fclose(fp);
}
原来的文件内容结果变成了这样的:
烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫8
烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫8
-858993460
烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫8
烫烫烫烫烫烫烫烫烫烫烫烫烫8
烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫8
烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫8
-858993460
烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫8
烫烫烫烫烫烫烫烫烫烫烫烫烫8