引自免费微信小程序:皆我百晓生
在C语言中,为了实现一个加载学生学籍信息到链表中的功能,你需要创建一个新的函数,这个函数将读取文本文件并逐行解析数据,然后将其插入到链表中。这里是一个详细的步骤和代码示例。
首先,确保已经定义了头文件包含、初始化链表、添加节点以及打印链表的函数。接下来,我们将编写load_student_info()函数,它会打开指定的文件,并将内容读入链表中。
以下是完整的代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// ... (其他已定义的函数)
void load_student_info(linklist** head, const char* filename) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("Error opening file: %s\n", filename);
return;
}
linklist* current = *head;
linklist* new_node;
while (!feof(file)) {
stu temp_student;
char line[200];
// 读取一行,直到遇到换行符或文件结束
fgets(line, sizeof(line), file);
// 如果读取的是空行或文件结束,跳出循环
if (line[0] == '\n' || feof(file))
break;
// 解析每一行数据
sscanf(line, "%s %d %s %d %s %f",
temp_student.info.name, &temp_student.info.id,
temp_student.info.sex, &temp_student.info.age,
temp_student.info.major, &temp_student.info.sort);
// 继续解析课程信息
for (int i = 0; i < 10 && !feof(file); ++i) {
fgets(line, sizeof(line), file);
if (line[0] == '\n')
continue;
sscanf(line, "%s %f %f %f %d",
temp_student.courses[i].name,
&temp_student.courses[i].score,
&temp_student.courses[i].credit,
&temp_student.courses[i].DKgrapoint,
&temp_student.courses[i].ismakeup);
}
// 创建新节点并将数据复制进去
new_node = (linklist*) malloc(sizeof(linklist));
memcpy(&new_node->data, &temp_student, sizeof(stu));
// 将新节点添加到链表中
if (*head == NULL) {
*head = new_node;
} else {
while (current->next != NULL)
current = current->next;
current->next = new_node;
}
}
fclose(file);
}
// ... (其他已定义的函数)
在这个代码中,我们首先打开文件,然后逐行读取数据。每读取一行,我们就使用sscanf()函数解析数据并填充临时的学生结构体temp_student。当处理完一条完整的学生信息后,我们会创建一个新的链表节点,并将temp_student的数据复制过去。接着,我们将新节点添加到链表的末尾。
注意:此代码没有处理错误情况,例如文件读取失败或内存分配失败。在实际应用中,你应该加入相应的错误处理代码。