关于C语言链表保存为文件的方法,我想建一个链表,把它存在文件中,下次打开时可以直接打开此链表。求方法

[复制链接]
查看11 | 回复1 | 2011-5-23 12:38:12 | 显示全部楼层 |阅读模式
这是我写的代码。如果按下面的有效代码的话只能读出链表的head值。如果按注释掉的来编译话,就直接出错了。还有其他方法实现吗!?
# include "stdio.h"
# include "stdlib.h"
# include "string.h"
# include "malloc.h"
struct student
{
char name[10];
char id[20];
float score;
struct student * next;
};
struct student * creat()//创建一个链表
{
        struct student * head;
        struct student * back;
        struct student * front;
        head=NULL;
        back=front=(struct student *)malloc(sizeof(struct student));
        printf("请输入学生姓名,学号和成绩:\n");
        scanf("%s %s %f",front->name,front->id,&front->score);
         int n=1;
         while(strcmp(front->name,"#")!=0)
        {
         
        n++;
        if(head==NULL)
                head=front;
        else
        {
       
back->next=front;
                 back=front;
                 front=(struct student *)malloc(sizeof(struct student));
                 scanf("%s %s %f",front->name,front->id,&front->score);
        }
        }
        back->next=NULL;
        FILE * fp;
        fp=fopen("student_list","a+");
        if((fp=fopen("student_list","a+"))==NULL)
        {
                printf("File open error!");
       
return NULL;
                exit(0);
        }
        else
        {
                fwrite(head,sizeof(struct student),n,fp);
                fclose(fp);
                return head;
        }
}
void print(struct student * head)//打印输出链表
{
struct student *p;
p=head;
if(p==NULL)
         {
        printf("The list is empty..!Please check.....!\n");

exit(0);
}
while(p!=NULL)
{
printf("%10s%20s%5.1f\n",p->name,p->id,p->score);
p=p->next;
}
}
void main()
{
struct student * head;
FILE *f;
/*f=fopen("student_list","a+");
if((f=fopen("student_list","a+"))!=NULL)
         for(int k=0;kname,head->id,head->score);
         }
else
{
        head=creat();
         for(int k=0;kname,head->id,head->score);
         }
}*/
head=creat();
f=fopen("student_list","a+");
fread(head,sizeof(struct student),1,f);
printf("%10s%20s%5.1f\n",head->name,head->id,head->score);
}

回复

使用道具 举报

千问 | 2011-5-23 12:38:12 | 显示全部楼层
不可能,下面是我的想法,你需要将链表的每一个结点的内容都按一定的格式写入到文件,下次打开时,先创建一个新结点,将它们按格式读入到这个新结点中,然后把新结点插入到链表尾部,接着再读入另一个结点,直到遇到文件尾feof();不懂就到群151988677,找千里
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行