C链表使用fread和fwrite写入文件和从文件读出
具体代码如下
typedef struct Lnode {
ElemType data;
struct Lnode *next;
}Lnode, *Linknode;
status SaveList(Linknode &L)
{
FILE *fp; char filename[30]; int i;
printf("input file name: ");
scanf("%s", filename);
if ((fp = fopen(filename, "wb")) == NULL)
{
printf("File open error\n ");
return 1;
}
Linknode head=NULL;
head = L->next;
while (head)
{
fwrite(&head->data,sizeof(ElemType), 1, fp);
head = head->next;
}
fclose(fp);
return OK;
}
status LoadList(Linknode &L)
{
FILE *fp; char filename[30];
int temp;
Linknode pHead=NULL;
printf("input file name: ");
scanf("%s", filename);
if ((fp = fopen(filename, "rb")) == NULL)
{
printf("File open error\n ");
return 1;
}
Linknode tail=L;
while (fread(&temp, sizeof(ElemType), 1, fp))
{
Linknode node = (Linknode)malloc(sizeof(Lnode));
node->data = temp;
tail->next = node;
tail = node;
tail->next = NULL;
}
fclose(fp);
return OK;
}