一个简单把文件里的数据传到链表里,把链表的数据传到文件里的程序,老是出问题。
#include <stdio.h>#include <stdlib.h>
struct data
{
int num;
};
struct student
{
struct data dat;
struct student *next;
};
struct student *lianbiao()
{
FILE *fp;
fp=fopen("1.txt","r+");
if(NULL == fp)
{
printf("文件读取失败!");
exit(1); //非0为非正常退出
}
struct student *head=(struct student *)malloc(sizeof(struct student));
struct data asd;
head->next=NULL;
while(0!=fread(&asd,sizeof(struct data),1,fp));
{
struct student *p=(struct student *)malloc(sizeof(struct student));
p->dat=asd;
p->next=NULL;
p->next=head->next;
head->next=p;
}
fclose(fp);
return head;
}
struct student *print(struct student *head)
{
struct student *p=head->next;
while(p!=NULL)
{
printf("%d",p->dat.num);
p=p->next;
}
}
struct student *add()
{
struct student *head=lianbiao();
// struct student *head=(struct student *)malloc(sizeof(struct student));
while(1)
{
char m;
struct student *p=(struct student *)malloc(sizeof(struct student));
printf("请输入添加的数据:");
scanf("%d",&p->dat.num);
getchar();
p->next=head->next;
head->next=p;
printf("是否继续添加Y or N");
scanf("%c",&m);
getchar;
if(m=='n'&&'N')
{
break;
}
}
return head;
}
void main()
{
FILE *fp;
fp=fopen("1.txt","w+");
struct student *head=(struct student *)malloc(sizeof(struct student));
head=add();
struct student *p=(struct student *)malloc(sizeof(struct student));
p=head;
while(p!=NULL)
{
fwrite(&p->dat,sizeof(struct student),1,fp);
p=p->next;
}
print(head);
fclose(fp);
}