#include<stdio.h>
#include<stdlib.h>
struct student
{int num;
struct student *next;
};
int main()
{FILE *fp;
struct student *head,*p1,*p2,*p;
int i,n;
printf("请输入建立学生表人数\n");
scanf("%d",&n);
p1=p2=(struct student *)malloc(sizeof(struct student));
scanf("%d",&p1->num);
head=p1=p2;
for(i=1;i<=n-1;i++)
{p1=(struct student *)malloc(sizeof(struct student));
scanf("%d",&p1->num);
p2->next=p1; //节点间链接
p2=p1;
}
p2->next=NULL; //赋值尾节点
if((fp=fopen("1015.txt","wb"))==NULL)
{printf("cannot open filc\n");
exit(0);
}
p=head;
while(p->next!=NULL) //写入数据
{if(fwrite(p,sizeof(struct student),1,fp)!=1)
{printf("数据保存失败\n");
fclose(fp);
exit(0);
}
p=p->next;
}
fclose(fp);
printf("写入数据成功\n");
if((fp=fopen("1015.txt","rb"))==NULL) //读取文件
{printf("cannot read file\n");
exit(0);
}
printf("成功读取数据\n");
head=NULL;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
while(!feof(fp)) //读取数据
{p1=(struct student *)malloc(sizeof(struct student));
fread(p1,sizeof(struct student),1,fp);
if(head==NULL)
head=p2=p1;
else
{p2->next=p1;
p2=p1;
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for(i=1;i<=n;i++)
{printf("%d ",p->num);
p=p->next;
}
fclose(fp);
}
本人估计~~~处错误了。运行结果不对。编译是没问题的
#include<stdlib.h>
struct student
{int num;
struct student *next;
};
int main()
{FILE *fp;
struct student *head,*p1,*p2,*p;
int i,n;
printf("请输入建立学生表人数\n");
scanf("%d",&n);
p1=p2=(struct student *)malloc(sizeof(struct student));
scanf("%d",&p1->num);
head=p1=p2;
for(i=1;i<=n-1;i++)
{p1=(struct student *)malloc(sizeof(struct student));
scanf("%d",&p1->num);
p2->next=p1; //节点间链接
p2=p1;
}
p2->next=NULL; //赋值尾节点
if((fp=fopen("1015.txt","wb"))==NULL)
{printf("cannot open filc\n");
exit(0);
}
p=head;
while(p->next!=NULL) //写入数据
{if(fwrite(p,sizeof(struct student),1,fp)!=1)
{printf("数据保存失败\n");
fclose(fp);
exit(0);
}
p=p->next;
}
fclose(fp);
printf("写入数据成功\n");
if((fp=fopen("1015.txt","rb"))==NULL) //读取文件
{printf("cannot read file\n");
exit(0);
}
printf("成功读取数据\n");
head=NULL;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
while(!feof(fp)) //读取数据
{p1=(struct student *)malloc(sizeof(struct student));
fread(p1,sizeof(struct student),1,fp);
if(head==NULL)
head=p2=p1;
else
{p2->next=p1;
p2=p1;
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for(i=1;i<=n;i++)
{printf("%d ",p->num);
p=p->next;
}
fclose(fp);
}
本人估计~~~处错误了。运行结果不对。编译是没问题的