怎样用C读取下头这样的文本文件到单向链表啊
怎样用C读取下面这样的文本文件到单向链表啊。。。
struct course{
char CourseName[5];
int CourseID;
int CourseSection;
};
typedef struct student{
char FirstName[100];
char LastNmae[100];
char SSN[15];
int nCourseAttd;
struct course StdCourse[10];
struct student *next;
}*stdList;
----- student.txt----
Lisa //First Name
Sanders //Last Name
111-11-1111 //SSN
3 //选课数量
ENEE 114 0103 //所选课程1 对应课程结构体1
CMSC 412 0101 //所选课程2 对应课程结构体2
ENME 515 0123 //所选课程3 对应课程结构体3
Bart //First Name
Simpson //Last Name
222-22-2222 //SSN
1 //选课数量
CMSC 412 0101 //所选课程1
***** //以此作为文件结束
------解决方案--------------------
struct course{
char CourseName[5];
int CourseID;
int CourseSection;
};
typedef struct student{
char FirstName[100];
char LastNmae[100];
char SSN[15];
int nCourseAttd;
struct course StdCourse[10];
struct student *next;
}*stdList;
----- student.txt----
Lisa //First Name
Sanders //Last Name
111-11-1111 //SSN
3 //选课数量
ENEE 114 0103 //所选课程1 对应课程结构体1
CMSC 412 0101 //所选课程2 对应课程结构体2
ENME 515 0123 //所选课程3 对应课程结构体3
Bart //First Name
Simpson //Last Name
222-22-2222 //SSN
1 //选课数量
CMSC 412 0101 //所选课程1
***** //以此作为文件结束
------解决方案--------------------
#include<stdio.h>
#include<stdlib.h>
struct course{
char CourseName[5];
int CourseID;
int CourseSection;
};
struct student{
char FirstName[100];
char LastName[100];
char SSN[15];
int nCourseAttd;
struct course StdCourse[10];
struct student *next;
};
void show(struct student *head);
int main()
{
FILE *fp;
struct student * head = NULL;
struct student *p;
int i;
if((fp = fopen("stu.txt", "r")) == NULL){
printf("无法打开文件stu.txt!\n");
exit(0);
}
head = (struct student *)malloc(sizeof(struct student));
if(head == NULL){
printf("空间不足!\n");
exit(0);
}
head->next = NULL;
while(!feof(fp)){
p = (struct student *)malloc(sizeof(struct student));
if(p == NULL){
printf("空间不足!\n");
exit(0);
}
fscanf(fp,"%s",p->FirstName);
fscanf(fp,"%s",p->LastName);
fscanf(fp,"%s",p->SSN);
fscanf(fp,"%d",&p->nCourseAttd);
for(i=0; i<p->nCourseAttd; i++){
fscanf(fp,"%s",p->StdCourse[i].CourseName);
fscanf(fp, "%d", &p->StdCourse[i].CourseID);
fscanf(fp, "%d", &p->StdCourse[i].CourseSection);
}
p->next = NULL;
p->next = head->next;
head->next = p;
}
show(head);
return 0;
}
void show(struct student *head){
struct student *p;
int i;
printf("以下是链表:\n");
p = head->next;
while(p){
printf("%s\n", p->FirstName);
printf("%s\n", p->LastName);
printf("%s\n", p->SSN);
printf("%d\n", p->nCourseAttd);
for(i=0; i<p->nCourseAttd; i++){
printf("%s %d %d\n", p->StdCourse[i].CourseName, p->StdCourse[i].CourseID,
p->StdCourse[i].CourseSection);
}