编写链表,链表里面随便搞点数据使用 fprintf 将链表中所有的数据,保存到文件中使用 fscanf 读取文件中的数据,写入链表中

#include "fun.h"

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

{

list_p H=creat();

write_data(H,1,1);

write_data(H,2,2);

write_data(H,5,3);

write_data(H,6,4);

write_data(H,7,5);

//printf_list(H);

//保存到文件中

list_p p=H;

FILE *fp=fopen("1.txt","w");

if(fp==NULL){return 1;}

while(1)

{

int ret=fprintf(fp,"%d ",p->next->data);

p=p->next;

if(ret==-1||p->next==NULL)

{

break;

}

}

fprintf(fp,"%d ",99);

fclose(fp);

//写入链表

list_p q=H;

FILE *fp2=fopen("1.txt","r");

if(fp2==NULL){return 1;}

while(1)

{

int rr=fscanf(fp2,"%d",&(q->next->data));

q=q->next;

if(rr==-1||q->next==NULL)

{

break;

}

}

printf_list(H);

return 0;

}

#include "fun.h"

list_p creat()

{

list_p H =(list_p)malloc(sizeof(list));

if(H==NULL)

{

return NULL;

}

H->len=0;

H->next =NULL;

return H;

}

list_p creat_node(int data)

{

list_p new=(list_p)malloc(sizeof(list));

new->data=data;

return new;

}

void write_data(list_p H,int data,int pos)

{

list_p new=creat_node(data);

list_p p = H;

for(int i=0;i<pos-1;i++)

{

p=p->next;

}

new->next=p->next;

p->next=new;

H->len++;

}

void printf_list(list_p H)

{

list_p p=H->next;

while(p!=NULL)

{

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

p=p->next;

}

}

#ifndef FUN_H

#define FUN_H

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>

typedef struct list

{

union

{

int len;

int data;

};

struct list *next;

}list,*list_p;

list_p creat();

list_p creat_node(int data);

void write_data(list_p H,int data,int pos);

void printf_list(list_p H);

#endif

相关推荐
繁星蓝雨10 小时前
C++的设计与演进大纲(如何从C语言一步步成长为C++)
c语言·开发语言·c++·c++历史·c++演进
yutian060610 小时前
C: Unix UTC 时间戳转为 UTC+8 北京时间
c语言·unix
彧azz13 小时前
数据结构:关于图的学习
c语言·数据结构·笔记·学习·算法
彧azz14 小时前
二叉搜索树学习记录
c语言·数据结构·笔记·算法
番茄灭世神18 小时前
汇顶模拟前端GH3220使用备忘录
c语言·单片机·传感器·模拟芯片·电生理信号处理
Brilliantwxx21 小时前
【STM32 】把 printf 搬到串口上 —— C 标准 IO 函数重定向与多文件工程搭建(实战串口电灯)
c语言·开发语言·stm32·单片机·嵌入式硬件·架构·ecmascript
wuminyu21 小时前
Kafka利用sendfile与Page Cache实现高性能传输剖析
java·linux·c语言·jvm·c++
亮_一个嵌入式新手1 天前
C语言Day21
c语言·开发语言
djarmy1 天前
MAIN.c(1): warning C318: can’t open file ‘STC8G.H’ 报错 解决 分析
c语言·开发语言·mongodb
李永奉1 天前
中科蓝讯SDK开发-BT893x 面条耳机连接vivo手机后连接APP端,最后手机端设置页面手动断开蓝牙连接,此时耳机端假断开
c语言·开发语言·嵌入式硬件·物联网·智能手机·电脑