希望大家帮忙看看这段代码
先运行一次程序,输入1执行creat(),save(),,再输入0退出;这样刚刚输入的数据就应该保存到phonebook里了,
再次打开程序,直接输入2,执行put()输出,却提示错误。
这是为什么?求大神帮忙
程序代码:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define N sizeof(struct person)
struct person
{
int num;//联系人序号
char name[20];//联系人名字
int phone;//联系人电话
struct person *next;
};
void menu();//主菜单
void put(struct person *head);//输出联系人
void save(struct person *head);//存储联系人
void add(struct person *head);//添加联系人
struct person *creat(int nn);
int i,j;
void main()
{
int aa;
while(1)
{
printf("输入\n");
scanf("%d",&aa);
fflush(stdin);
switch(aa)
{
case 1: head=creat(1);
save(head);break;
case 2: put(head);break;
case 3: add(head);
break;
case 0: exit(0);
}
}
}
struct person *creat(int nn)
{
int n=0;
int no;//记录联系人序号
no=nn;
struct person *head,*p1,*p2;
p1=p2=(struct person *)malloc(N);
p1->num=no;
printf("输入联系人姓名:");
gets(p1->name);
printf("输入联系人5位号码:");
scanf("%d",&p1->phone);
head=NULL;
while(p1->phone!=0)
{
n=n+1;
if(n==1)head=p1;
else p2->next=p1;
p2=p1;
p1=(struct person *)malloc(N);
fflush(stdin);
printf("输入联系人姓名:");
gets(p1->name);
no++;
p1->num=no;
printf("输入联系人5位号码:");
scanf("%d",&p1->phone);
}
p2->next=NULL;
return head;
}
void save(struct person *head)
{
FILE *fp;
if((fp=fopen("PhoneBook.dat","wb"))==NULL)
{
printf("打开错误");
return;
}
struct person *p;
p=head;
if(head!=NULL)
do
{
if(fwrite(p,sizeof(struct person),1,fp)!=1)
{printf("写入错误");}
p=p->next;
}while(p!=NULL);
fclose(fp);
}
void put(struct person *head)
{
FILE *fp;
struct person *p;
if((fp=fopen("PhoneBook.dat","rb"))==NULL)
{
printf("打开错误");
return;
}
p=head;
while(fread(p,sizeof(struct person),1,fp))
{
printf("%d\t%s\t%d\t\n",p->num,p->name,p->phone);
p++;
}
fclose(fp);
}






