69,366
社区成员
发帖
与我相关
我的任务
分享
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;
ret = fread(p,sizeof(struct shop ),1,fp);
printf("ret is %d\n",ret);
}
i++;
printf("%d\n",i);
}
没读到数据时会返回0;
读最完最后一个数据时,最后的文件结束符是0x00还没读,所以还会读一次,没有成功读取,但是分配了空间,所以多读了一次。
#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;
}