c语言链表文件存入链表并读取
时间: 2024-06-01 20:05:53 浏览: 18
C语言中的链表是一种常用的数据结构,它可以动态地存储和访问数据。在文件操作中,我们可以通过将链表中的数据存入文件中,也可以通过读取文件中的数据来构造链表。下面是一个简单的示例,演示了如何将链表中的数据存入文件并读取:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
void insert(Node **head, int data) {
Node *new_node = (Node*)malloc(sizeof(Node));
new_node->data = data;
new_node->next = *head;
*head = new_node;
}
void print_list(Node *head) {
Node *current = head;
while(current != NULL) {
printf("%d ", current->data);
current = current->next;
}
}
void save_list(Node *head, const char* filename) {
FILE *fp = fopen(filename, "w");
Node *current = head;
while(current != NULL) {
fprintf(fp, "%d ", current->data);
current = current->next;
}
fclose(fp);
}
void load_list(Node **head, const char* filename) {
FILE *fp = fopen(filename, "r");
int data;
while(fscanf(fp, "%d ", &data) != EOF) {
insert(head, data);
}
fclose(fp);
}
int main() {
Node *head = NULL;
insert(&head, 3);
insert(&head, 5);
insert(&head, 7);
printf("Original list: ");
print_list(head);
save_list(head, "list.txt");
printf("\nList saved to file.\n");
Node *new_head = NULL;
load_list(&new_head, "list.txt");
printf("Loaded list: ");
print_list(new_head);
return 0;
}
```
在这个示例中,我们定义了一个链表结构体`Node`,包含了一个整数类型的数据`data`和一个指向下一个节点的指针`next`。我们通过`insert`函数向链表中插入新的节点,并通过`print_list`函数打印链表中的所有数据。
在`save_list`函数中,我们打开一个文件,并将链表中的每个节点的数据依次写入文件中。在`load_list`函数中,我们打开这个文件,并逐行读取文件中的数据,然后通过`insert`函数将这些数据插入到一个新的链表中。
在`main`函数中,我们先创建一个链表并向其中插入一些数据,然后调用`save_list`函数将链表中的数据存入一个文件中。接着,我们调用`load_list`函数读取这个文件,并构造出一个新的链表。最后,我们分别打印原始链表和新的链表中的所有数据。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)