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;

}

相关推荐
码农不惑7 小时前
2025.06.27-14.44 C语言开发:Onvif(二)
c语言·开发语言
凌肖战8 小时前
力扣网C语言编程题:在数组中查找目标值位置之二分查找法
c语言·算法·leetcode
BreezeJuvenile9 小时前
数据结构与算法分析课设:一元多项式求值
c语言·课程设计·数据结构与算法分析·一元多项式计算
悲伤小伞10 小时前
linux_git的使用
linux·c语言·c++·git
气质、小青年!11 小时前
【排序算法】
c语言·数据结构
智者知已应修善业11 小时前
【51单片机节日彩灯控制器设计】2022-6-11
c语言·经验分享·笔记·单片机·嵌入式硬件·51单片机
开-悟12 小时前
嵌入式编程-使用AI查找BUG的启发
c语言·人工智能·嵌入式硬件·bug
Natsume171017 小时前
嵌入式开发:GPIO、UART、SPI、I2C 驱动开发详解与实战案例
c语言·驱动开发·stm32·嵌入式硬件·mcu·架构·github
shaun200117 小时前
华为c编程规范
c语言
MeshddY18 小时前
(超详细)数据库项目初体验:使用C语言连接数据库完成短地址服务(本地运行版)
c语言·数据库·单片机