c语言将数据写入文件(用链表实现)

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
删除链表节点并将链表重新写入文件的过程大致如下: 1. 打开文件,将链表读入内存。 2. 遍历链表,找到需要删除的节点,并删除它。 3. 关闭文件,重新打开文件并以写模式打开。 4. 将新的链表写入文件。 5. 关闭文件。 下面是一个简单的示例代码: ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构体 typedef struct node { int data; struct node *next; } Node; // 从文件中读取链表 Node *read_list_from_file(char *filename) { FILE *fp = fopen(filename, "r"); if (fp == NULL) { printf("Error: cannot open file %s\n", filename); return NULL; } Node *head = NULL; Node *tail = NULL; int data; while (fscanf(fp, "%d", &data) == 1) { Node *node = (Node *)malloc(sizeof(Node)); node->data = data; node->next = NULL; if (head == NULL) { head = node; tail = node; } else { tail->next = node; tail = node; } } fclose(fp); return head; } // 将链表写入文件 void write_list_to_file(char *filename, Node *head) { FILE *fp = fopen(filename, "w"); if (fp == NULL) { printf("Error: cannot open file %s\n", filename); return; } Node *node = head; while (node != NULL) { fprintf(fp, "%d\n", node->data); node = node->next; } fclose(fp); } // 删除链表节点 void delete_node(Node **head, int data) { Node *prev = NULL; Node *curr = *head; while (curr != NULL) { if (curr->data == data) { if (prev == NULL) { *head = curr->next; } else { prev->next = curr->next; } free(curr); return; } prev = curr; curr = curr->next; } } int main() { char *filename = "list.txt"; // 从文件中读取链表 Node *head = read_list_from_file(filename); // 删除节点 delete_node(&head, 3); // 将链表写入文件 write_list_to_file(filename, head); // 释放链表内存 Node *node = head; while (node != NULL) { Node *tmp = node; node = node->next; free(tmp); } return 0; } ``` 在该示例代码中,`read_list_from_file` 函数用于读取文件并构建链表,`write_list_to_file` 函数用于将链表写入文件,`delete_node` 函数用于删除链表中指定的节点。在 `main` 函数中,我们先读取链表,然后删除链表中的一个节点,最后将新的链表写入文件。注意,我们在删除节点后,需要释放该节点所占用的内存。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值