请给我一个非常完整的可以读写文件的链表代码
时间: 2023-04-09 22:00:36 浏览: 61
以下是一个可以读写文件的链表代码,希望能够帮到你:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void insert(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
void writeListToFile(struct Node* node, char* filename) {
FILE* fp = fopen(filename, "w");
while (node != NULL) {
fprintf(fp, "%d ", node->data);
node = node->next;
}
fclose(fp);
}
void readListFromFile(struct Node** head_ref, char* filename) {
FILE* fp = fopen(filename, "r");
int data;
while (fscanf(fp, "%d", &data) != EOF) {
insert(head_ref, data);
}
fclose(fp);
}
int main() {
struct Node* head = NULL;
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
insert(&head, 4);
insert(&head, 5);
printf("Linked List: ");
printList(head);
char* filename = "list.txt";
writeListToFile(head, filename);
struct Node* new_head = NULL;
readListFromFile(&new_head, filename);
printf("\nLinked List read from file: ");
printList(new_head);
return 0;
}
```
这个代码实现了一个链表,可以插入数据、打印链表、将链表写入文件、从文件中读取链表。你可以根据自己的需要进行修改和扩展。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)