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

}

相关推荐
六毛的毛33 分钟前
重排链表问题
数据结构·链表
东华万里1 小时前
第十四篇 操作符详讲
c语言·学习·大学生专区
linsa_pursuer4 小时前
回文链表算法
java·算法·链表
李绍熹4 小时前
C语言数组与指针示例
c语言·开发语言
杨福瑞4 小时前
数据结构:队列
c语言·数据结构
charlie1145141915 小时前
深入理解CC++的编译与链接技术9:动态库细节
c语言·开发语言·c++·学习·动态库
EXtreme355 小时前
【数据结构】打破线性思维:树形结构与堆在C语言中的完美实现方案
c语言·数据结构·算法··heap·完全二叉树·topk
电子_咸鱼5 小时前
【QT——信号和槽(1)】
linux·c语言·开发语言·数据库·c++·git·qt
枫叶丹48 小时前
【Qt开发】Qt窗口(九) -> QFontDialog 字体对话框
c语言·开发语言·数据库·c++·qt
神圣的大喵16 小时前
平台无关的嵌入式通用按键管理器
c语言·单片机·嵌入式硬件·嵌入式·按键库