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

   2025-02-16 6720
核心提示:在C语言中,可以使用文件操作相关的函数来将链表中的数据存入文件中。下面是一个简单的示例代码:#include stdio.h#include stdl

在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” 的文件中。最后释放链表内存。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言