温馨提示×

c语言怎么将链表中数据存入文件

小亿
198
2023-10-16 22:14:49
栏目: 编程语言

在C语言中,可以使用文件操作相关的函数来将链表中的数据存入文件中。下面是一个简单的示例代码:

#include <stdio.h>
#include <stdlib.h>
// 链表节点结构定义
struct Node {
int data;
struct Node* next;
};
// 将链表中的数据存入文件
void saveListToFile(struct Node* head, const char* filename) {
// 打开文件以写入模式
FILE* file = fopen(filename, "w");
if (file == NULL) {
printf("无法打开文件!\n");
return;
}
// 遍历链表,将数据写入文件
struct Node* current = head;
while (current != NULL) {
fprintf(file, "%d\n", current->data);
current = current->next;
}
// 关闭文件
fclose(file);
}
int main() {
// 创建链表
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
struct Node* second = (struct Node*)malloc(sizeof(struct Node));
struct Node* third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
// 将链表中的数据存入文件
saveListToFile(head, "data.txt");
// 释放链表内存
free(head);
free(second);
free(third);
return 0;
}

以上代码示例中,首先定义了一个链表节点结构 struct Node,包含一个整数型的数据和一个指向下一个节点的指针。然后定义了一个函数 saveListToFile,接收链表头节点和文件名作为参数,通过打开文件、遍历链表和写入数据的方式将链表中的数据存入文件。在 main 函数中,创建了一个简单的链表,并调用 saveListToFile 函数将链表中的数据存入名为 “data.txt” 的文件中。最后释放链表内存。

0