IO-DAY1

1.用fprintf将链表数据保存到文件中

2用fscanf将文件中数据写入链表

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

#include<unistd.h>

typedef int datatype;

typedef struct link_list

{

union

{

int len;

datatype data;

};

struct link_list *next;

}link_list,*link_p;

link_p create_head()

{

link_p L = (link_p)malloc(sizeof(link_list));

if(L==NULL)

{

printf("空间申请失败\n");

return NULL;

}

L->len=0;

L->next=NULL;

return L;

}

//创建结点

link_p create_node(datatype data)

{

link_p new = (link_p)malloc(sizeof(link_list));

if(new==NULL)

{

printf("空间申请失败\n");

return NULL;

}

new->data = data;

return new;

}

//头插

void insert_head(link_p H,datatype data)

{

if(H==NULL)

{

printf("入参为空,请检查\n");

return;

}

link_p new = create_node(data);

new->next = H->next;

H->next = new;

H->len++;

}

void out_put_link(link_p H)

{

if(H==NULL)

{

printf("入参为空,请检查\n");

return;

}

link_p p = H->next;

while(p!=NULL)

{

printf("%d->",p->data);

p = p->next;

}

printf("NULL\n");

void save(char *filename)

{

FILE *w=fopen(filename,"w");

if (w == NULL)

{

return 1;

}

link_p p=H->next;

for (int i = 0; i <H->len; i++)

{

fprintf(w,"%d",p->data);

p=p->next;

}

fclose(w);

}void show(char *filename)/*输出文件*/

{

FILE *fp=fopen(filename,"r");

link_list arr[100];

if (fp== NULL)

{

return 1;

}

for (int i = 0; i <H->len; i++)

{

fscanf(fp,"%d",&(arr[i].data));

printf("%d\n", arr[i].data);

}

fclose(fp);

}

int main(int argc, char *argv[])

{

link_p H=create_head();

insert_head(H,1);

insert_head(H,3);

insert_head(H,5);

insert_head(H,7);

insert_head(H,9);

out_put_link(H);

save(filename);

free(p);

show(filename);

return 0;

}

相关推荐
晓131323 分钟前
第二章 【C语言篇:入门】 C 语言基础入门
c语言·算法
jiang_changsheng25 分钟前
环境管理工具全景图与深度对比
java·c语言·开发语言·c++·python·r语言
前端玖耀里4 小时前
Linux C/C++ 中系统调用与库函数调用的区别
linux·c语言·c++
进击的小头5 小时前
设计模式与C语言高级特性的结合
c语言·设计模式
代码无bug抓狂人5 小时前
C语言之可分解的正整数(蓝桥杯省B)
c语言·开发语言·算法
历程里程碑6 小时前
21:重谈重定义理解一切皆“文件“及缓存区
linux·c语言·开发语言·数据结构·c++·算法·缓存
恶魔泡泡糖7 小时前
51单片机I2C-EEPROM
c语言·单片机·嵌入式硬件·51单片机
jiang_changsheng7 小时前
MCP协议的核心架构基础
c语言·开发语言·c++·python·comfyui
1+α7 小时前
工业通讯中的“顶梁柱”——RS485科普
c语言·stm32·嵌入式硬件·网络协议
晓13137 小时前
第三章 【C语言篇:结构化编程】 分支循环数组函数
c语言