链表的存储与读取问题
#include<stdio.h>
#include<string.h>
#include<process.h>
#include<malloc.h>
struct bank
{
long account;
char name[20];
char password[10];
float saving;
struct bank *pNext;
};
struct bank *pHead,*pEnd;
struct bank *temp;
void create();
void read(struct bank *tempHead);
void list(struct bank *temp);
void write(struct bank *tempBank);
void main()
{
int choose;
if((pHead=(struct bank*)malloc(sizeof(struct bank)))==NULL)
{
printf("创建链表失败!");
exit(1);
}
if((temp=(struct bank*)malloc(sizeof(struct bank)))==NULL)
{
printf("创建临时链表失败!");
exit(1);
}
pHead=pEnd=NULL;
while(1)
{
printf("\n\n请输入选择:");
scanf("%d",&choose);
if(choose==1)
{
create();
temp=pHead;
write(temp);
continue;
}
if(choose==2)
{
read(temp);
list(pHead);
continue;
}
if(choose==3)
exit(0);
}
}
void write(struct bank *tempBank)
{
FILE *fp;
if((fp=fopen("bank.obj","ab+"))==NULL)
{
printf("数据文件创建失败!");
exit(1);
}
while(1)
{
if(tempBank->pNext==NULL)
{
fwrite(tempBank,sizeof(struct bank),1,fp);
if(ferror(fp))
{
printf("数据写入失败!");
exit(1);
}
fclose(fp);
return;
}
tempBank=tempBank->pNext;
}
}
void create()
{
float F_F_F_F=0.0; //无意义定义,只是为了提醒VC6.0需要处理浮点数
struct bank *pCurrentBank;
if((pCurrentBank=(struct bank*)malloc(sizeof(struct bank)))==NULL)
{
printf("创建链表失败!");
exit(1);
}
printf("\n\n*******************");
printf("\n 数据录入开始!");
printf("\n\n帐号: ");
scanf("%d",&pCurrentBank->account);
printf("\n姓名: ");
scanf("%s",&pCurrentBank->name);
printf("\n密码: ");
scanf("%s",&pCurrentBank->password);
printf("\n存款: ");
scanf("%f",&pCurrentBank->saving);
if(pHead==NULL)
pHead=pCurrentBank;
else
pEnd->pNext=pCurrentBank;
pEnd=pCurrentBank;
pEnd->pNext=NULL;
}
void list(struct bank *tempHead)
{
if(tempHead==NULL)
{
printf("暂无数据!\n\n");
return;
}
while(tempHead)
{
printf("帐号:%d\t\t姓名:%s\t\t存款:%0.2f\n\n",\
tempHead->account,tempHead->name,tempHead->saving);
tempHead=tempHead->pNext;
}
}
void read(struct bank * tempHead)
{
FILE *fp;
if((fp=fopen("bank.obj","rb"))==NULL)
{
printf("数据文件打开失败!");
exit(1);
}
while(!feof(fp))
{
fread(tempHead,sizeof(struct bank),1,fp);
if(pHead==NULL)
pHead=tempHead;
else
pEnd->pNext=tempHead;
pEnd=tempHead;
pEnd->pNext=NULL;
}
fclose(fp);
return;
}
在这个程序中,如果注释掉文件存储和读取的代码,链表的输入和显示功能都已正常。
但是,写入链表后,无法正常读取,读取的链表居然只有最后输入的一个节点数据。
而如果在read()函数中的fread()指令后面跟一条printf()指令来显示数据,则全部数据都会显示出来,只是最后一个数据会重复显示一次。
初学C,请各位大哥大姐帮忙!