标题:链表中的东西写到文件中读出来的问题
只看楼主
gxppa2006
Rank: 1
等 级:新手上路
帖 子:178
专家分:0
注 册:2007-2-27
 问题点数:0 回复次数:3 
链表中的东西写到文件中读出来的问题
#include <stdio.h>
#include <malloc.h>
typedef struct wage_info
{
char name[20];
char department[100];
float base_pay;
float allowance;
float total;
struct wage_info *next;
}wage;
main()
{
wage *head,*p,*s;
FILE *fp;
float c;
if((fp=fopen("paydata","a+"))==NULL)
{
printf("file is not exist.\n");
fp=fopen("paydata","wb");
}
fp=fopen("paydata","a+");
head=(wage *)malloc(sizeof(wage));
p=head;
printf("Please input the name department base_pay allowance,ends with name is 0:\n");
do
{
s=(wage *)malloc(sizeof(wage));
scanf("%s,%s,%f,%f",&s->name,&s->department,&s->base_pay,&s->allowance);
c=(s->base_pay)+(s->allowance);
printf("%s %s %f %f %f",s->name,s->department,s->base_pay,s->allowance,c);
p->next=s;
p=s;
}while(p->base_pay!=0);
p->next=NULL;
head=head->next;
free(p);
if(fwrite(head,sizeof(wage),1,fp)!=1)
{
printf("can not write files!\n");
}
fclose(fp);
fp=fopen("paydata","rb");
fread(head,sizeof(wage),1,fp);
fclose(fp);
getch();
}
搜索更多相关主题的帖子: 链表 wage float 文件 
2007-04-14 23:29
jmy2446267
Rank: 1
等 级:新手上路
帖 子:46
专家分:0
注 册:2007-4-14
得分:0 

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
typedef struct a1
{
int b1;
struct a2
{
int b2;
struct a3
{
int b3;
struct a3 *next;
}c3;
struct a2 *next;
}c2;
struct a1 *next;
}r;
void main()
{
r *a=(r *)malloc(sizeof(r)),*b=(r *)malloc(sizeof(r));
FILE *fp=fopen("c:\\a.dat","wb+");
r *c=(r *)malloc(sizeof(r));
long int g;
clrscr();
printf("input a->b1:");scanf("%d",&a->b1);
printf("input a->c2.b2:");
scanf("%d",&a->c2.b2);
printf("input a->c2.c3.b3:");
scanf("%d",&a->c2.c3.b3);
a->c2.c3.next=(struct a3 *)malloc(sizeof(struct a3));
printf("input a->c2.c3.next->b3:");
scanf("%d",&a->c2.c3.next->b3);
a->c2.next=(struct a2 *)malloc(sizeof(struct a2));
printf("input a->c2.next->b2:");
scanf("%d",&a->c2.next->b2);
fwrite(a,sizeof(r),1,fp);
rewind(fp);
fread(b,sizeof(r),1,fp);
printf("%d\t%d\t%d\t%d\t%d",b->b1,b->c2.b2,
b->c2.c3.b3,b->c2.c3.next->b3,b->c2.next->b2);
fseek(fp,0l,SEEK_END);
g=ftell(fp);
printf("\n%ld\t%ld",g,g/sizeof(r));
getch();
fclose(fp);

}


你可以看看我的这段代码,相信会对你有一定帮助。
这里关于将互相嵌套的链表写入文件,不过我觉得棘手的是链表中含指针,指针写入文件是否有意义的问题。
当内存释放掉后这个文件还有意义吗?因为写入文件的指针已经失去意义了。那么指针所指向的数据也就找不到了。怎么解决呢?


仗剑天下,快意恩仇!
2007-04-15 10:31
风过无影
Rank: 1
等 级:新手上路
威 望:1
帖 子:346
专家分:0
注 册:2005-5-14
得分:0 

可以;看看学习


成都IT人才网 www.
2007-04-15 13:56



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-131944-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.119269 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved