|
1.正在做学生管理系统,深刻学习C语言
2.已经可以生成链表(见creat函数),并把生成的链表保存到student.txt文件(见store函数).
3.并且可以打印出生成的链表(见print函数)。
4.不能实现:将student.txt文件的数据读入链表中 (见load函数),求大神指导!
环境VC++ 6.0
上代码:
- #include <stdio.h>
- #include <stdlib.h>
- #include "malloc.h"
- #include "process.h"
- #define LEN sizeof(struct student)
- int n;
- struct student
- {
- long num;
- float score;
- struct student *next;
- };
- struct student *creat(void)
- {
- struct student *head;
- struct student *p1,*p2;
- n=0;
- p1=p2=(struct student *)malloc(LEN);
- scanf("%ld,%f",&p1->num,&p1->score);
- head=NULL;
- while(p1->num!=0)
- {
- n=n+1;
- if(n==1)head=p1;//把首地址给链表头
- else p2->next=p1;//指针下移
- p2=p1;//更新p2指针
- p1=(struct student *)malloc(LEN);//申请新的地址&更新p1指针
- scanf("%ld,%f",&p1->num,&p1->score);
- }
- p2->next=NULL;
- return(head);
- }
- struct student *print(struct student *head)
- {
- struct student *p;
- p=head;
- printf("链表中共用%d条记录\n",n);
- if(head!=NULL)
- {
-
- do
- {
- printf("%ld,%5.1f\n",p->num,p->score);
- p=p->next;
- }
- while(p!=NULL);
- }
- return(head);
- }
- /*
- function:将生成结构体中的数据保存到文件中
- time:2014-5-16 9:42:49
-
- version:V1.0
- input:要存入链表的首地址
- output:void
- 链表默认保存到student.txt文件中
- */
- void store(struct student *head)
- {
- FILE *fp;
- struct student *p;
- fp=fopen("student.txt","w+");//新建文件
- if(fp==NULL)
- {
- printf("open file failed");
- exit(0);
- }
- p=head;
- if(head!=NULL)
- {
- do
- {
- fprintf(fp,"%ld,%f",p->num,p->score);
- p=p->next;
- }
- while(p!=NULL);
- }
- fprintf(fp,"0");
- fclose(fp);//关闭文件
- printf("Linked list store is ok!\n");
-
- }
- /*
- function:将文件中的数据读入到链表中
-
- time:2014-5-16 10:12:23
- version:V1.0
- input:void
- ouput:返回链表的头指针
- 读取默认文件 student.txt
- */
- struct student *load(void)
- {
- FILE *fp;
- struct student *head;
- struct student *p1,*p2;
- fp=fopen("student.txt","r");//打开文件
- rewind(fp);
- if(fp==NULL)
- {
- printf("open file failed");
- exit(0);
- }
-
- n=0;
- head=NULL;
- p1=p2=(struct student *)malloc(LEN);
- fscanf(fp,"%ld,%f",&p1->num,&p1->score);
- while(p1->num!=0)
- {
- n=n+1;
- if(n==1)head=p1;
- else p2->next=p1;
- p2=p1;
- p1=(struct student *)malloc(LEN);
- fscanf(fp,"%ld,%f",&p1->num,&p1->score);
- }
- p2->next=NULL;
- fclose(fp);//关闭文件
- return(head);
- }
复制代码 |
阿莫论坛20周年了!感谢大家的支持与爱护!!
曾经有一段真挚的爱情摆在我的面前,我没有珍惜,现在想起来,还好我没有珍惜……
|