逐行读取文件以构造
Read a file line by line to struct
我想读取一个如下所示的文件:
Spyros 1
George 2
John 3
我想将每个学生存储在一个结构中:
typedef struct studentR *student;
struct studentR{
char name[MAXSTRING];
int id;
student next;
};
我已经编写了以下代码,它可以满足我的要求,但仅限于第一行。我怎样才能把它移到下一行?
while(fscanf(fp, "%s %d", st->name, &st->id) != EOF){
l = list_push_back(l, st->name, st->id);
}
这里是list_push_back
//enters the new student in the end of the list
list list_push_back(list l, char *name, int id){
student new_student = (student)malloc(sizeof(struct studentR));
assert(new_student);
strcpy(new_student->name, name);
new_student->id = id;
new_student->next = NULL;
//push payload(stsudent data) at the top if the list is empty
if (list_isempty(l))
{
l->head = new_student;
l->tail = new_student->next;
l->size++;
}else{
//push the payload(student data) at the bottom if the list is NOT empty
student last = (student)malloc(sizeof(struct studentR));
assert(last);
last->next = new_student;
l->tail = new_student;
l->size++;
}
return l;
}
该代码的错误包括:
- 永远不要在添加到空列表的情况下正确设置
tail
。
- add-to-not-empty-list 情况下的内存泄漏(两次)。
- 在 add-to-not-empty-list 的情况下添加一个节点,但在这样做时会泄漏内存。
该函数应如下所示:
list list_push_back(list l, const char *name, int id)
{
student new_student = malloc(sizeof *new_student);
assert(new_student);
strcpy(new_student->name, name);
new_student->id = id;
new_student->next = NULL;
if (l->size == 0)
{
l->head = new_student;
}
else
{
l->tail->next = new_student;
}
l->tail = new_student;
l->size++;
return l;
}
那是全部。
我想读取一个如下所示的文件:
Spyros 1
George 2
John 3
我想将每个学生存储在一个结构中:
typedef struct studentR *student;
struct studentR{
char name[MAXSTRING];
int id;
student next;
};
我已经编写了以下代码,它可以满足我的要求,但仅限于第一行。我怎样才能把它移到下一行?
while(fscanf(fp, "%s %d", st->name, &st->id) != EOF){
l = list_push_back(l, st->name, st->id);
}
这里是list_push_back
//enters the new student in the end of the list
list list_push_back(list l, char *name, int id){
student new_student = (student)malloc(sizeof(struct studentR));
assert(new_student);
strcpy(new_student->name, name);
new_student->id = id;
new_student->next = NULL;
//push payload(stsudent data) at the top if the list is empty
if (list_isempty(l))
{
l->head = new_student;
l->tail = new_student->next;
l->size++;
}else{
//push the payload(student data) at the bottom if the list is NOT empty
student last = (student)malloc(sizeof(struct studentR));
assert(last);
last->next = new_student;
l->tail = new_student;
l->size++;
}
return l;
}
该代码的错误包括:
- 永远不要在添加到空列表的情况下正确设置
tail
。 - add-to-not-empty-list 情况下的内存泄漏(两次)。
- 在 add-to-not-empty-list 的情况下添加一个节点,但在这样做时会泄漏内存。
该函数应如下所示:
list list_push_back(list l, const char *name, int id)
{
student new_student = malloc(sizeof *new_student);
assert(new_student);
strcpy(new_student->name, name);
new_student->id = id;
new_student->next = NULL;
if (l->size == 0)
{
l->head = new_student;
}
else
{
l->tail->next = new_student;
}
l->tail = new_student;
l->size++;
return l;
}
那是全部。