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

}

相关推荐
yuyousheng12 分钟前
CentOS7更换为阿里源
linux·c语言
进击的小头29 分钟前
结构型模式:适配器模式(C语言实现与底层实战)
c语言·适配器模式
EmbedLinX1 小时前
一文理解后端核心概念:同步/异步、阻塞/非阻塞、进程/线程/协程
linux·服务器·c语言·网络
人间不清醒ab2 小时前
FREERTOS检测任务栈内存情况
c语言·单片机
Amber7623 小时前
嵌入式C函数参数设计深度解析:指针与值传递的实战艺术
c语言·开发语言
2401_841495644 小时前
【LeetCode刷题】K 个一组翻转链表
数据结构·python·算法·leetcode·链表·翻转链表·迭代翻转
散峰而望5 小时前
【数据结构】假如数据排排坐:顺序表的秩序世界
java·c语言·开发语言·数据结构·c++·算法·github
爱编码的小八嘎5 小时前
c语言对话-2.空引用
c语言
zh_xuan5 小时前
LeeCode 61. 旋转链表
数据结构·c++·算法·leetcode·链表
Дерек的学习记录6 小时前
二叉树(下)
c语言·开发语言·数据结构·学习·算法·链表