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

}

相关推荐
xueyinan10 分钟前
小刚说C语言刷题—1088求两个数M和N的最大公约数
c语言
_Itachi__10 分钟前
LeetCode 热题 100 114. 二叉树展开为链表
linux·leetcode·链表
王RuaRua2 小时前
[数据结构]7. 堆-Heap
c语言·数据结构·算法·链表
似水এ᭄往昔4 小时前
【数据结构】——队列
c语言·数据结构·c++·链表
水水沝淼㵘4 小时前
嵌入式开发学习日志(数据结构--双链表)Day21
c语言·数据结构·学习·算法·排序算法
ElseWhereR5 小时前
反转链表 - 简单
数据结构·链表
czxyvX5 小时前
023-C语言预处理详解
c语言
夜晚中的人海6 小时前
【C语言】初阶数据结构相关习题(二)
c语言·开发语言·数据结构
范纹杉想快点毕业8 小时前
以项目的方式学QT开发(三)——超详细讲解(120000多字详细讲解,涵盖qt大量知识)逐步更新!
c语言·开发语言·c++·qt·mysql·算法·命令模式
敲代码的瓦龙8 小时前
STL?list!!!
c语言·开发语言·数据结构·c++·windows·list