C语言怎么将双向链表用文件写 举例
时间: 2024-01-05 12:02:48 浏览: 89
以下是一个简单的示例,演示如何将双向链表用文件写入和读取:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义双向链表节点结构体
typedef struct Node {
int data;
struct Node *prev;
struct Node *next;
} Node;
// 定义双向链表结构体
typedef struct List {
Node *head;
Node *tail;
} List;
// 初始化双向链表
void initList(List *list) {
list->head = list->tail = NULL;
}
// 新建双向链表节点
Node *newNode(int data) {
Node *node = (Node*)malloc(sizeof(Node));
node->data = data;
node->prev = node->next = NULL;
return node;
}
// 在双向链表尾部插入节点
void insert(List *list, int data) {
Node *node = newNode(data);
if (list->head == NULL) {
list->head = list->tail = node;
} else {
node->prev = list->tail;
list->tail->next = node;
list->tail = node;
}
}
// 将双向链表写入文件
void writeListToFile(List *list, const char *filename) {
FILE *fp = fopen(filename, "wb");
if (fp == NULL) {
printf("Failed to open file %s\n", filename);
return;
}
Node *node = list->head;
while (node != NULL) {
fwrite(&node->data, sizeof(int), 1, fp);
node = node->next;
}
fclose(fp);
}
// 从文件中读取数据并构建双向链表
void readListFromFile(List *list, const char *filename) {
FILE *fp = fopen(filename, "rb");
if (fp == NULL) {
printf("Failed to open file %s\n", filename);
return;
}
int data;
while (fread(&data, sizeof(int), 1, fp) == 1) {
insert(list, data);
}
fclose(fp);
}
// 打印双向链表
void printList(List *list) {
Node *node = list->head;
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
int main() {
List list;
initList(&list);
// 在双向链表中插入数据
insert(&list, 1);
insert(&list, 2);
insert(&list, 3);
// 将双向链表写入文件
writeListToFile(&list, "list.dat");
// 清空双向链表
initList(&list);
// 从文件中读取数据并构建双向链表
readListFromFile(&list, "list.dat");
// 打印双向链表
printList(&list);
return 0;
}
```
在上面的示例中,我们定义了一个Node结构体作为双向链表的节点,其中包含双向指针prev和next,用于指向前驱节点和后继节点。我们定义了一个List结构体作为双向链表,其中包含头部指针head和尾部指针tail。我们提供了一些基本操作,如初始化双向链表、新建节点、在链表尾部插入节点等。我们使用fwrite()函数和fread()函数将双向链表写入和读取到文件中,其中fwrite()函数将节点中的数据写入到文件中,fread()函数将从文件中读取数据并构建双向链表。最后,我们提供了一个打印双向链表的函数printList()来验证读取操作是否成功。
阅读全文
相关推荐


















