这一串代码编译成功,但是显示结果不对,求解
已知文件中存有一组已按从小到大排序的一组数,下面程序的功能是:将从键盘输入的一个数插入到文件中,使文件中的数还能保持从小到大的顺序不变。#include<stdio.h>
struct data {int x;struct data *next;};
main()
{FILE *fp;
struct data *head,*p1,*p2,*p;
if((fp=fopen("A.txt","r"))==NULL) {printf("error");getch();exit();};
head=p2=NULL;
while(!feof(fp))
{ p1=p2=head=(struct sata *)malloc(sizeof(struct data));
fscanf(fp,"%d",&p1->x);printf("%d ",p1->x);
if(head==NULL) head=p1;
else p2->next=p1;
p2=p1;
}
p2->next=NULL; fclose(fp);
printf("\nInput a data:");
p=(struct data*)malloc(sizeof(struct data));
scanf("%d",&p->x); p1=head;
while(p1!=NULL)
{ if(p1->x>p->x)break;
p2=p1;p1=p1->next; }
if(p1==head){head=p;p->next=p1;}
else {p->next=p1;p2->next=p;}
fp=fopen("A.txt","w");
p1=head;
while(p1!=NULL) {printf("%d ",p1->x);fprintf(fp,"%d ",p1->x);p1=p1->next;}
fclose(fp);
getch();}