关于C语言中,链表数据的文件储存和提取。

我是这样想的,希望高手能指正一下。
先建立一个链表,然后把链表的每一个结点都保存在文件中。下次需要数据的时候,从文件中按照结构体定义的结构,一块一块的把数据读出来。
我自己写了一个小程序,但是运行起来有故障,希望高手能帮忙看看是什么地方错了。谢谢啊~~~~
或者高手能提供一个更好的思路来解决问题也可以。我是一个初学者,还需要多多指教。
程序比较多,不好意思,给10个金币。
程序如下:
1,链表保存程序(出现的问题是,最后一个数据保存不进去)
#include "stdafx.h"
#include "stdlib.h"
#define N 5
int main()
{
struct fac
{
int data;
struct fac* next;
}*phead;
phead=(struct fac *)malloc(sizeof(struct fac));
FILE *fp=fopen("d:\\ctest\\exam7","wb");
phead->next=NULL;
struct fac *ptail=phead;
int i,value;
for(i=0;i<N;i++)
{
struct fac *p=(struct fac*)malloc(sizeof(struct fac));
printf("%dvalue=",i);
scanf("%d",&value);
p->data=value;
ptail->next=p;
p->next=NULL;
ptail=p;
}
struct fac *pinput;
pinput=phead->next;
do
{
fwrite(pinput,sizeof(struct fac),1,fp);
pinput=pinput->next;
}
while(pinput->next!=NULL);
fclose(fp);
2,链表输出程序(问题是,如果我不用for循环语句,而是用while语句。因为假设如果我不知道数据的明确的个数,for语句就用不了了。现在的这个程序是我知道数据一共5个)
#include "stdafx.h"
#include "stdlib.h"
int main()
{
struct fac
{
int data;
struct fac *next;
}*phead;
int i;
FILE *fp=fopen("d:\\ctest\\exam7","rb");
struct fac *p;
phead=(struct fac*)malloc(sizeof(struct fac));
p=(struct fac*)malloc(sizeof(struct fac));
fread(p,sizeof(struct fac),1,fp);
for(i=0;i<5;i++)
{
printf("%d\n",p->data);
p=p->next;
p=(struct fac*)malloc(sizeof(struct fac));
fread(p,sizeof(struct fac),1,fp);

}
}

当把链表已经确定的时候,就可以依次存入文件。

和平时链表的遍历一样,每读取一个节点内容就进行一次存入操作。

不过要注意几个部分的检查:

    内存空间是否分配成功

    是否成功存入到文件中

    在工作完成之后,是否将以后不会用到的变量清空和删除。


按照问题要求的代码如下:

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;

}//储存链表到文件

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-02-28
do
{
fwrite(pinput,sizeof(struct fac),1,fp);
pinput=pinput->next;
}
while(pinput->next!=NULL);
这个理解了,你那个就不难解决了啊。现在你要写最后一个结点信息,加入执行
pinput=pinput->next;这句后pinput就指向了最后一个结点,此时你还没写它。可是接下来的
while判断就让你退出了循环,你可以将while改成while(pinput==NULL);

第二个问题,可以用while循环啊,判断条件就是读到文件尾部就退出。
while(!feof(fp))
{
fscanf(); //你从磁盘读数据,fp会自动移动
}
这种形式。本回答被提问者和网友采纳
相似回答