编写函数,将学生信息按照格式存储在txt文件中。 3. 编写函数,将txt文件中的学生信息读取到单链表中,每一个节点表示一个学生信息
时间: 2023-04-03 12:00:58 浏览: 48
好的,我可以回答这个问题。以下是代码示例:
存储学生信息到txt文件中:
```c
#include <stdio.h>
#include <stdlib.h>
struct student {
char name[20];
int age;
float score;
};
void save_to_file(struct student stu[], int n) {
FILE *fp;
fp = fopen("students.txt", "w");
if (fp == NULL) {
printf("Failed to open file.\n");
exit(1);
}
for (int i = ; i < n; i++) {
fprintf(fp, "%s %d %.2f\n", stu[i].name, stu[i].age, stu[i].score);
}
fclose(fp);
}
```
读取txt文件中的学生信息到单链表中:
```c
#include <stdio.h>
#include <stdlib.h>
struct student {
char name[20];
int age;
float score;
struct student *next;
};
struct student *read_from_file() {
FILE *fp;
fp = fopen("students.txt", "r");
if (fp == NULL) {
printf("Failed to open file.\n");
exit(1);
}
struct student *head = NULL;
struct student *p = NULL;
while (!feof(fp)) {
struct student *node = (struct student *)malloc(sizeof(struct student));
fscanf(fp, "%s %d %f", node->name, &node->age, &node->score);
node->next = NULL;
if (head == NULL) {
head = node;
p = node;
} else {
p->next = node;
p = node;
}
}
fclose(fp);
return head;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)