c语言:将链表数据写入到文件,将数据读入链表

#include "linklist.h"

link_p createHead()

{

link_p H = (link_p)malloc(sizeof(link));

if (H == NULL)

{

printf("空间申请失败\n");

return NULL;

}

H->next = NULL;

H->len = 0;

return H;

}

link_p createNode(int data)

{

link_p node = (link_p)malloc(sizeof(link));

if (node == NULL)

{

printf("空间申请失败\n");

return NULL;

}

node->next = NULL;

node->data = data;

return node;

}

void insertHead(link_p H,int data)

{

if (H == NULL)

{

printf("入参为空,请检查\n");

return;

}

link_p node = createNode(data);

node->next = H->next;

H->next = node;

H->len++;

}

void insertTail(link_p H,int data)

{

if (H == NULL)

{

printf("入参为空,请检查\n");

return;

}

link_p node = createNode(data);

link_p current = H;

while (current->next != NULL)

current = current->next;

node->next = current->next;

current->next = node;

H->len++;

}

void outPutDataToFile(link_p H, char *pathname)

{

FILE* fp = fopen(pathname, "w");

if (fp == NULL)

{

perror("");

return;

}

link_p current = H;

while (current->next != NULL)

{

current = current->next;

fprintf(fp,"%d ",current->data);

}

}

link_p readDataFromFile(char* pathname)

{

FILE* fp = fopen(pathname, "r");

if (fp == NULL)

{

perror("readDataFromFile");

return NULL;

}

link_p H = createHead();

int tmp;

while (1)

{

int ret = fscanf(fp,"%d",&tmp);

if (ret != 1)

break;

insertTail(H, tmp);

}

//outPut(H);

return H;

}

void outPut(link_p H)

{

if (H == NULL)

{

printf("入参为空,请检查\n");

return;

}

link_p current = H;

while ((current = current->next) != NULL)

printf("%d\t", current->data);

printf("\n");

}

相关推荐
Alfred king10 小时前
面试150 LRU缓存
链表·缓存·哈希表·lru·双向链表
遇见尚硅谷14 小时前
C语言:游戏代码分享
c语言·开发语言·算法·游戏
GGBondlctrl15 小时前
【leetcode】字符串,链表的进位加法与乘法
算法·leetcode·链表·字符串相加·链表相加·字符串相乘
Jess0716 小时前
归并排序递归法和非递归法的简单简单介绍
c语言·算法·排序算法
打野二师兄16 小时前
LeetCode经典题解:21、合并两个有序链表
算法·leetcode·链表
双叶83617 小时前
(C++)STL标准库(vector动态数组)(list列表)(set集合)(map键值对)相关对比,基础教程
c语言·开发语言·数据结构·c++·list
j_xxx404_19 小时前
c语言:字符函数和字符串函数
c语言·开发语言
apocelipes20 小时前
C23和C++26的#embed嵌入资源指南
c语言·c++·开发工具和环境·c23·c++26
liweiweili1261 天前
GPT和MBR分区
c语言
菜鸟12号1 天前
详解Linux下多进程与多线程通信(一)
linux·c语言·嵌入式·进程与线程