c语言,关于保存链表到文件和从文件装载链表(高手请进,急)

来源:百度知道 编辑:UC知道 时间:2024/05/10 08:07:12
老师给了以下两段参考,但是我搞不明白...就是要把链表保存到文件addrbook中,那以下两段应该怎么改?

第一段:
SaveToFile(struct address *p, FILE *fp)
{
if(p=NULL)
do {
fwrite(p,sizeof(struct address),1,fp);
p=p->next;
}while(p!=NULL);
}

第二段:
struct address *head;
int n=0;
int load(FILE *fp, ) //读取文件数据,建立链表
{ struct address *p1,*p2;
head= (struct address *) malloc(sizeof(struct address));
if( fread(head, sizeof(struct address),1,fp)!=1) {
free(head);
head=NULL;
return(0);
}
p2=head; n++;
while( !feof(fp)){
p1= (struct address *) malloc(sizeof(struct address));
fread(p1, sizeof(struct address),1,fp);
p2->next=p1;
p2=p1;
n++;
}
p2->next=NULL;
return(n);
}
er..

拿去用吧~
#include <stdio.h>
#include <malloc.h>
#include <string.h>

struct address
{
int a;
int b;
char c;
address *next;
};

void SaveToFile(struct address *p, FILE *fp)
{
if(p != NULL)
{
do
{
fwrite(p, sizeof(struct address), 1, fp);
p = p->next;
}
while(p != NULL);
}
}

int load(FILE *fp, struct address **head, int &n ) //读取文件数据,建立链表
{
struct address *p1,*p2;
*head = (struct address *) malloc(sizeof(struct address));
memset(*head, 0, sizeof(struct address));
if( fread(*head, sizeof(struct address), 1, fp) != 1)
{
free(*head);
*head = NULL;
return(0);
}
p2 = *head;
n++;
while( !feof(fp))
{
p1 = (struct address *) malloc(sizeof(struct address));
fread(p1, sizeof(struct address), 1, fp);
p2->next = p1;
p2