读书人

C语言.dat资料读成链表后读不到最

发布时间: 2013-07-01 12:33:04 作者: rapoo

C语言.dat文件,读成链表后,读不到最后一条
文件中保存了三条struct shop信息,但是前两条读出来了,而第三条内容错了
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
struct shop
{
long date;
int buy_money;
int money;
char style[10];
int time;
char place[50];

};
struct shoplink
{
long date;
int buy_money;
int money;
char style[10];
int time;
char place[50];
struct shoplink * next;
};
struct shoplink * plink()
{
FILE *fp;
struct shoplink *p,*head;
int i=0;
head = p=(struct shoplink *)malloc(sizeof(struct shoplink));
if((fp=fopen("shop.dat","rb"))==NULL)
{
printf("cannot open file\n");
exit(0);
}
while(!feof(fp))
{ if(i==0)
fread(p,sizeof(struct shop),1,fp);
else
{
p->next=(struct shoplink *)malloc(sizeof(struct shoplink));
p=p->next;
fread(p,sizeof(struct shop ),1,fp);

}
i++;
}
fclose(fp);
p->next=NULL;


return head;
}
void main()
{
int i=0;
struct shoplink *p;
p=plink();
while(p!=NULL)
{
printf("%d%s\n",i,p->style);
p=p->next;
i++;
}
getchar();
} C 链表 .dat文件
[解决办法]



#include<string.h>
#include<stdlib.h>
#include<stdio.h>
struct shop
{
long date;
int buy_money;
int money;
char style[10];
int time;
char place[50];

};
struct shoplink
{
long date;
int buy_money;
int money;
char style[10];
int time;
char place[50];
struct shoplink * next;
};
struct shoplink * plink()
{
FILE *fp;
struct shoplink *p,*head;
int i=0;
head = p=(struct shoplink *)malloc(sizeof(struct shoplink));
if((fp=fopen("shop.dat","rb"))==NULL)
{
printf("cannot open file\n");
exit(0);
}
while(!feof(fp))
{ if(i==0)


fread(p,sizeof(struct shop),1,fp);
else
{
p->next=(struct shoplink *)malloc(sizeof(struct shoplink));
p=p->next;
fread(p,sizeof(struct shop ),1,fp);

}
i++;
}
fclose(fp);
p->next=NULL;


return head;
}
void shop_write()
{
struct shop t;
t.date = 1;
FILE *fp;
t.buy_money =3;
t.money = 4;
strcpy(t.style, "hello");
t.time = 3;
strcpy(t.place, "good");
if((fp=fopen("shop.dat","wb+"))==NULL)
{
printf("cannot open file\n");
exit(0);
}
fwrite(&t,sizeof(struct shop),1,fp);
t.buy_money =3;
t.money = 4;
strcpy(t.style, "helco");
t.time = 3;
strcpy(t.place, "good");
fwrite(&t,sizeof(struct shop),1,fp);
t.buy_money =3;
t.money = 4;
strcpy(t.style, "telco");
t.time = 3;
strcpy(t.place, "good");
fwrite(&t,sizeof(struct shop),1,fp);
fflush(fp);

}
void main()
{
int i=0;
struct shoplink *p;
shop_write();
p=plink();
while(p!=NULL)
{
printf("%d%s\n",i,p->style);
p=p->next;
i++;
}
getchar();
}


[解决办法]

struct shoplink * plink()
{
FILE *fp;
struct shoplink *p,*head;
int i=0;
if((fp=fopen("D:\\shop.dat","rb"))==NULL)
{
printf("cannot open file\n");
exit(0);
}
//下面这段改一下。。
while(1)
{
int ret;
struct shoplink *q=(struct shoplink *)malloc(sizeof(struct shoplink));
ret = fread(q, sizeof(struct shop), 1, fp);
if(ret == 0){
free(q);
break;
}
if(i==0){
head = p = q;
}
else{
p->next=q;
p=p->next;
}
i++;
}
fclose(fp);


p->next=NULL;
return head;
}

读书人网 >C语言

热点推荐