如何把链表写入文件~和读出文件

来源:百度知道 编辑:UC知道 时间:2024/07/01 13:16:18
#include "stdio.h"
#include "conio.h"
#include "math.h"
struct node
{int data;
struct node *next;};
typedef struct node AA;
AA *gz()
{AA *h,*r,*b; int a;
r=(AA *)malloc(sizeof(AA));
h=r;
printf("qing shu ru\n");
scanf("%d",&a);
while(a)
{ b=(AA *)malloc(sizeof(AA));
b->data=a;
r->next=b;
r=b;
scanf("%d",&a);}链表
r->next='\0';
return h;}

sh()
{AA *to=0,*pp=0,*p,t[10],*head=gz(); int i;
FILE *fp;
if(fp=fopen("d:\\zhuziliang","wb"))
printf("yi da kai\n");

head=head->next;链表头指针
while(head)写入文件

fopen("d:\\zhuziliang","wb")
改为
fopen("d:\\zhuziliang","wb+")

------------------------------------------

fread(t,sizeof(AA),1,fp);
printf("%d->",t[0].data);

改为

i=0;
while (!feof(fp))
{
fread(&t[i],sizeof(AA),1,fp);
printf("%d->",t[i++].data);
}
fclose(fp);

--------------------------------------------

用到了malloc()函数,所以要包含stdlib.h头文件

修改后的完整程序如下:
//---------------------------------------------------------------------------

#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
#include "math.h"
struct node
{int data;
struct node *next;
};
typedef struct node AA;

AA *gz(void)
{AA *h,*r,*b; int a;
r=(AA *)malloc(sizeof(AA));
h=r;
printf("qing shu ru\n