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");

}

相关推荐
智者知已应修善业15 分钟前
【51单片机单按键控制2个LED循环闪烁】2022-12-7
c语言·经验分享·笔记·嵌入式硬件·51单片机
笑口常开xpr40 分钟前
Linux动静态库开发基础:静态库与动态库的编译构建、链接使用及问题排查
linux·c语言·动态库·静态库
三体世界2 小时前
测试用例全解析:从入门到精通(1)
linux·c语言·c++·python·功能测试·测试用例·测试覆盖率
程序员东岸2 小时前
C语言入门指南:字符函数和字符串函数
c语言·笔记·学习·程序人生·算法
kyle~11 小时前
排序---插入排序(Insertion Sort)
c语言·数据结构·c++·算法·排序算法
张晓~1833994812112 小时前
短视频矩阵源码-视频剪辑+AI智能体开发接入技术分享
c语言·c++·人工智能·矩阵·c#·php·音视频
纵有疾風起14 小时前
数据结构中的排序秘籍:从基础到进阶的全面解析
c语言·数据结构·算法·排序算法
夜猫逐梦15 小时前
【Lua】Windows 下编写 C 扩展模块:VS 编译与 Lua 调用全流程
c语言·windows·lua
_OP_CHEN15 小时前
数据结构(C语言篇):(十三)堆的应用
c语言·数据结构·二叉树·学习笔记·堆排序··top-k问题
量子炒饭大师16 小时前
收集飞花令碎片——C语言关键字typedef
c语言·c++·算法