#include <string.h>
#include <stdlib.h>
#include <stdio.h>
struct shares
{
char name[20];
char num[20];
int
date;
long price;
char sort[15];
char company[20];
struct shares * next;
};
#define LEN sizeof(struct shares)
#define NUM 2
int n=0;
struct shares * input()// 录入函数//
{
struct shares * head=0;
struct shares *p1,*p2;
while(n<NUM)
{
p1=(struct shares *)malloc(LEN);
scanf("%s %s %d %ld %s %s",p1->name,p1->num,&p1->date,&p1->price,p1->sort,p1->company);
n=n+1;
if(n==1)
head=p1;
else
p2->next=p1;
p2=p1;
}
p2->next=NULL;
return(head);
}
void save(struct shares * head)
//保存记录//
{
FILE * fp;
struct shares *p = head;
int i;
if((fp=fopen("F:\\data.txt","wb"))==NULL)
{
printf("cannot open the file\n");
return;
}
while(p)
//循环的条件换一下。(p+i)->next!=0,那第三心爱那个是无法输出的,因为当i=2时,条件不成了了,不能写入文件
{
if(fwrite(p,LEN,1,fp)!=1)
printf("file write error\n");
p = p->next;
}
fclose(fp);
}
void read(struct shares *head)
//读取数据//
{
int i;
struct shares *pp = head;
FILE *fp;
fp=fopen("F:\\data.txt","rb");
for(i=0;pp!=NULL;i++)
//和在save中的错误一样,改变循环条件
{
fread(pp,LEN,1,fp);
printf("\n%s %s %d %ld %s %s\n",pp->name,pp->num,pp->date,pp->price,pp->sort,pp->company);
pp = pp->next;
}
}
int main()
{
struct shares * head;
head=input();
save(head);
read(head);
return 0;
}
还有写文件如果不是二进制文件的话,最好不要用fwrite和fread改用fprintf和fscanf