//把学生信息存放在txt文件中,读取数据,数据//放在单链表中。具体代码怎么写
时间: 2023-03-30 16:04:49 浏览: 58
您好,以下是一个简单的示例代码,用于将学生信息存储在txt文件中,并将数据放在单链表中:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义学生结构体
typedef struct student {
char name[20];
int age;
char gender[10];
struct student *next;
} Student;
// 读取txt文件中的学生信息
void read_student_info(Student **head) {
FILE *fp;
fp = fopen("student.txt", "r");
if (fp == NULL) {
printf("无法打开文件\n");
return;
}
while (!feof(fp)) {
Student *new_student = (Student *)malloc(sizeof(Student));
fscanf(fp, "%s %d %s", new_student->name, &new_student->age, new_student->gender);
new_student->next = *head;
*head = new_student;
}
fclose(fp);
}
// 输出学生信息
void print_student_info(Student *head) {
while (head != NULL) {
printf("姓名:%s,年龄:%d,性别:%s\n", head->name, head->age, head->gender);
head = head->next;
}
}
int main() {
Student *head = NULL;
read_student_info(&head);
print_student_info(head);
return ;
}
希望对您有所帮助。