C语言怎么将链表存入文件中
时间: 2023-09-26 17:07:59 浏览: 90
在C语言中,将链表存入文件需要以下步骤:
1. 打开文件,使用fopen函数,指定文件名和文件打开模式,如"w"表示写入模式。
2. 遍历链表,将链表中的每个节点的数据写入文件中,可以使用fwrite函数。
3. 关闭文件,使用fclose函数,释放资源。
下面是一个示例代码,假设链表中每个节点的数据类型为int:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
struct Node {
int data;
struct Node* next;
};
// 将链表写入文件中
void writeListToFile(struct Node* head, const char* filename) {
FILE* fp = fopen(filename, "w");
if (fp == NULL) {
printf("无法打开文件\n");
return;
}
// 遍历链表,写入文件
struct Node* p = head;
while (p != NULL) {
fwrite(&(p->data), sizeof(int), 1, fp);
p = p->next;
}
fclose(fp);
}
int main() {
// 创建一个简单的链表
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
struct Node* node1 = (struct Node*)malloc(sizeof(struct Node));
node1->data = 2;
head->next = node1;
struct Node* node2 = (struct Node*)malloc(sizeof(struct Node));
node2->data = 3;
node1->next = node2;
node2->next = NULL;
// 将链表写入文件中
writeListToFile(head, "list.txt");
// 释放链表内存
struct Node* p = head;
while (p != NULL) {
struct Node* next = p->next;
free(p);
p = next;
}
return 0;
}
```
运行以上代码后,会在当前目录下创建一个名为list.txt的文件,其中存储着链表中每个节点的数据。