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

}

相关推荐
鱼很腾apoc12 小时前
【MySQL】第4期 用户管理与 C 语言连接编程详解
linux·服务器·c语言·mysql·connector/c
himobrinehacken14 小时前
位运算揭秘:左右移与符号位陷阱
c语言·c++·算法·安全
水饺编程16 小时前
第2章:Linux 基础,rm 命令
linux·c语言·汇编
夏虫不可与之言冰16 小时前
第三课 点亮 LED 与定时器非阻塞闪烁
c语言·c++·vscode·单片机·嵌入式硬件·物联网
JasmineX-117 小时前
数据结构(笔记)——顺序栈
c语言·数据结构·笔记
2401_8628808217 小时前
嵌入式Linux系统移植与驱动开发完整指南
linux·c语言·驱动开发
我叫洋洋19 小时前
Cadence 16.6 从 OrCAD Capture 原理图到 Allegro PCB 全流程(含 5 个常见坑)
c语言·eda·嘉立创
水饺编程20 小时前
第2章:Linux 基础,关机命令
linux·c语言·汇编
Brilliantwxx20 小时前
【Linux】IO(上)全篇:文件本质、C 接口、系统调用与文件描述符
linux·运维·服务器·c语言
坐看风云变幻21 小时前
《嵌入式工程师的软硬件修仙之路》第 2 期|C 语言筑基:指针与内存模型
c语言·开发语言