#include<string.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct shebei
{ int xuhao
char bianhao[40]
char didian[40]
char mingcheng[40]
char zhuangtai[40]
struct shebei*next
}SHEBEI
int n
void print(struct shebei*head)
struct shebei*creat()
void RW_File(SHEBEI *head)
void main()
{ struct shebei*head
head=creat()
RW_File(head)
printf("\nji xu jia you o !!!\n")
}
struct shebei*creat()
{ struct shebei*p1,*p2
struct shebei*head
n=0
p1=p2=(struct shebei*)malloc(sizeof(struct shebei))
head=NULL
printf("shu ru xu hao:\n")
scanf("%d",&p1->xuhao)
printf("shu xu bian hao:\n")
scanf("%s",p1->bianhao)
printf("shu ru di dian:\n")
scanf("%s",p1->didian)
printf("shu ru ming cheng:\n")
scanf("%s",p1->mingcheng)
printf("shu ru zhuang tai:\n")
scanf("%s",p1->zhuangtai)
while(p1->xuhao!=0)
{ n=n+1
if(n==1)
head=p1
else
p2->next=p1
p2=p1
p1=(struct shebei*)malloc(sizeof(struct shebei))
printf("shu ru xu hao:\n")
scanf("%d",&p1->xuhao)
printf("shu xu bian hao:\n")
scanf("%s",p1->bianhao)
printf("shu ru di dian:\n")
scanf("%s",p1->didian)
printf("shu ru ming cheng:\n")
scanf("%s",p1->mingcheng)
printf("shu ru zhuang tai:\n")
scanf("%s",p1->zhuangtai)
}
p2->next=NULL
return(head)
}
void RW_File(SHEBEI *head)/*head是你刚刚创建的链表的头指针*/
{
SHEBEI SingleInfo[20]
FILE *fp
int i=0
if((fp=fopen("d:\\shebei","wb+"))==NULL)
{
printf("can not open file")
exit(1)
}
while(head)
{
fwrite(head,sizeof(SHEBEI),1,fp)
head = head->next
}
rewind(fp)/*到这里已经把链表写入到d盘的shebei文件中*/
while(!feof(fp))
{
fread(&SingleInfo[i],sizeof(SHEBEI),1,fp)
i++
}
fclose(fp)
}
拿去用吧~#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<10i++)
{
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=0i<10i++)
{
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)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)