当前位置: 代码迷 >> C语言 >> 链表中的东西写到文件中读出来的问题
  详细解决方案

链表中的东西写到文件中读出来的问题

热度:126   发布时间:2007-04-14 23:29:07.0
链表中的东西写到文件中读出来的问题
#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  文件  

----------------解决方案--------------------------------------------------------

#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);

}


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


----------------解决方案--------------------------------------------------------

可以;看看学习


----------------解决方案--------------------------------------------------------
  相关解决方案