求教!将链表写入文件中,并从文件中读取。我自己的代码贴上了,文件部分写的有问题,请大神们帮忙看看!感谢!
#include <stdio.h>#include <stdlib.h>
#include <iostream>
using namespace std;
#include<iomanip>
#include<string.h>
#define N 30
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef struct
{
char num[10]; //套餐编号
}TaoCan;
typedef struct LNode
{
TaoCan *data;
LNode *next;
}LNode,*LinkList;
Status InitList(LinkList &L)
{
L=new LNode;
L->next=NULL;
return OK;
}
void save(LinkList &p);
void load(LinkList &P);
void CreatList(LinkList &L,int n);
int main()
{
LinkList L,p;
InitList(L);
int n;
p=L;
cout<<"请输入套餐数:"; cin>>n;
CreatList(L,n);
save(p);
load(p);
return 0;
}
void save(LinkList &p)
{
FILE *fp;
if((fp=fopen("f:\\dx.txt","ab+"))==NULL)
{
printf("open fail\n");
exit(0);
}
fseek(fp,0,SEEK_END);
while(p)
{
if(fwrite(p,sizeof(struct LNode),1,fp)!=1)
{
printf("file write error\n");
exit(0);
}
p=p->next;
}
fclose(fp);
}
void load(LinkList &p)
{
FILE *fp;
int i;
if((fp=fopen("f:\\dx.txt","rb"))==NULL)
{
printf("open fail\n");
exit(0);
}
while(p)
{
if(fread(p,sizeof(struct LNode),1,fp)!=1)
{
printf("file write error\n");
exit(0);
}
cout<<"套餐编号: "<<p->data->num<<endl;
p=p->next;
}
fclose(fp);
}
void CreatList(LinkList &L,int n)
{
L=new LNode;
L->next=NULL;
LinkList p;
int i;
for(i=0;i<n;i++)
{
p=new LNode;
cout<<"请输入套餐编号: "; cin>>p->data->num;
p->next=L->next;L->next=p;
}
}