如何将一个文件里的多个相同结构的结构体逐一输出并存储在一个链表里
时间: 2024-05-08 20:17:49 浏览: 10
首先,需要定义一个结构体来存储每个相同结构体的数据,例如:
```
typedef struct {
int id;
char name[50];
float score;
} Student;
```
然后,需要定义一个链表结构体来存储每个相同结构体的数据:
```
typedef struct node {
Student data;
struct node* next;
} Node;
```
接下来,可以使用文件操作函数从文件中读取每个相同结构体的数据,并将其存储在链表中,例如:
```
Node* head = NULL;
Node* current = NULL;
FILE* fp = fopen("students.txt", "r");
if (fp != NULL) {
while (!feof(fp)) {
Student student;
if (fscanf(fp, "%d %s %f", &student.id, student.name, &student.score) == 3) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = student;
node->next = NULL;
if (head == NULL) {
head = node;
current = node;
} else {
current->next = node;
current = node;
}
}
}
fclose(fp);
}
```
这样,就可以读取文件中的每个相同结构体的数据,并将其存储在链表中。最后,可以遍历链表并输出每个相同结构体的数据,例如:
```
Node* node = head;
while (node != NULL) {
printf("ID: %d, Name: %s, Score: %f\n", node->data.id, node->data.name, node->data.score);
node = node->next;
}
```
同时,也可以将链表中的数据写入到文件中,例如:
```
Node* node = head;
FILE* fp = fopen("output.txt", "w");
while (node != NULL) {
fprintf(fp, "%d %s %f\n", node->data.id, node->data.name, node->data.score);
node = node->next;
}
fclose(fp);
```