由于字数限制,我没办法把所有源代码写出来.
下面是我定的一个结构体,链表什么的都写好了!!就链表怎么写入文件,和从文件中读到链表里面该怎么做!
求高手指点!!!
struct book
{
char num[20]; //书号
char name[10]; //书名
int jinjia; //进价
int shoujia; //售价
int shuliang; //库存数量
int shouchu; //售出
struct book *next;
};
当把链表已经确定的时候,就可以依次存入文件。
和平时链表的遍历一样,每读取一个节点内容就进行一次存入操作。
不过要注意几个部分的检查:
内存空间是否分配成功
是否成功存入到文件中
在工作完成之后,是否将以后不会用到的变量清空和删除。
按照问题要求的代码如下:
Consumer* read_list()
{
FILE *fp;
if ((fp = fopen("CONSUMER.dat", "rb")) == NULL)
{
printf("无法读取 CONSUMER.dat\n");
return NULL;
}
int sign;
Consumer *s,*p,*head;
head= (Consumer*)malloc(SIZE_C);
if (head == NULL)
{
printf("读取失败!内存空间申请不足!\n");
return NULL;
}
fseek(fp, 0, SEEK_END);
if (ftell(fp) == 0)
{
return NULL;
}
p = head;
p->next = NULL;
while (feof(fp))
{
s = (Consumer*)malloc(SIZE_C);
//fread(s, SIZE_C, 1, fp);
fread(s, sizeof(char), SIZE_C, fp);
p->next = s;
p = s;
p->next = NULL;
}
fclose(fp);
return head;
}//读取文件到链表
int save_consumer(Consumer *p)
{
FILE *fp;
Consumer *head;
head = p;//p为已经构建好的链表
//if ((fp = fopen("CONSUMER.dat", "ab+")) == NULL)
if ((fp = fopen("CONSUMER.dat", "wb")) == NULL)
{
printf("无法打开 CONSUMER.dat!\n");
return -1;
}
while (p != NULL)
{
//fwrite(p, SIZE_C, 1, fp);
fwrite(p, sizeof(char), SIZE_C, fp);
p = p->next;
}
fclose(fp);
return 1;
}//储存链表到文件