编写函数,将学生信息按照格式存储在txt文件中。 3. 编写函数,将txt文件中的学生信息读取到单链表中,每一个节点表示一个学生信息
时间: 2023-04-03 07:00:55 浏览: 66
好的,我可以回答这个问题。以下是编写函数将学生信息按照格式存储在txt文件中的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct student {
char name[20];
int age;
char gender[10];
} Student;
void save_student_info(Student* s) {
FILE* fp;
fp = fopen("students.txt", "a");
fprintf(fp, "%s %d %s\n", s->name, s->age, s->gender);
fclose(fp);
}
int main() {
Student s1 = {"Tom", 18, "male"};
Student s2 = {"Lucy", 19, "female"};
save_student_info(&s1);
save_student_info(&s2);
return ;
}
```
以下是编写函数将txt文件中的学生信息读取到单链表中的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student {
char name[20];
int age;
char gender[10];
struct student* next;
} Student;
void read_student_info(Student** head) {
FILE* fp;
fp = fopen("students.txt", "r");
if (fp == NULL) {
printf("Failed to open file.\n");
return;
}
char line[100];
while (fgets(line, 100, fp) != NULL) {
Student* s = (Student*)malloc(sizeof(Student));
sscanf(line, "%s %d %s", s->name, &s->age, s->gender);
s->next = *head;
*head = s;
}
fclose(fp);
}
int main() {
Student* head = NULL;
read_student_info(&head);
Student* p = head;
while (p != NULL) {
printf("%s %d %s\n", p->name, p->age, p->gender);
p = p->next;
}
return ;
}
```