发布网友 发布时间:2022-04-24 06:40
共1个回答
热心网友 时间:2022-06-17 01:58
拿去用吧~
#include<stdio.h>
#include<malloc.h>
#include<string.h>
structaddress
{
inta;
intb;
charc;
address*next;
};
voidSaveToFile(structaddress*p,FILE*fp)
{
if(p!=NULL)
{
do
{
fwrite(p,sizeof(structaddress),1,fp);
p=p->next;
}
while(p!=NULL);
}
}
intload(FILE*fp,structaddress**head,int&n)//读取文件数据,建立链表
{
structaddress*p1,*p2;
*head=(structaddress*)malloc(sizeof(structaddress));
memset(*head,0,sizeof(structaddress));
if(fread(*head,sizeof(structaddress),1,fp)!=1)
{
free(*head);
*head=NULL;
return(0);
}
p2=*head;
n++;
while(!feof(fp))
{
p1=(structaddress*)malloc(sizeof(structaddress));
fread(p1,sizeof(structaddress),1,fp);
p2->next=p1;
p2=p1;
n++;
}
p2->next=NULL;
return(n);
}
voidmain()
{
structaddress*head;
intn=0;
structaddress*Test[10]={0};
inti=0;
FILE*fp=NULL;
for(;i<10;i++)
{
Test[i]=(structaddress*)malloc(sizeof(structaddress));
if(Test[i]!=NULL)
{
memset(Test[i],0,sizeof(structaddress));
//输入你的数据(a,b,c)
//如下
Test[i]->a=100+i;//不用则注释掉
}
}
for(i=0;i<10;i++)
{
if(i<10)
{
Test[i]->next=Test[i+1];//将结构指针连成链表
}
}
if((fp=fopen("addrbook","wb"))!=NULL)
{
SaveToFile(Test[0],fp);
fclose(fp);
}
if((fp=fopen("addrbook","rb"))!=NULL)
{
load(fp,&head,n);
}
}