编写链表,链表里面随便搞点数据使用 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

相关推荐
恶魔泡泡糖12 小时前
51单片机矩阵按键
c语言·算法·矩阵·51单片机
松涛和鸣12 小时前
DAY52 7-Segment Display/GPIO/Buttons/Interrupts/Timers/PWM
c语言·数据库·单片机·sqlite·html
Echo缘13 小时前
关于在.cpp文件中包含c的头文件,编译报错问题
c语言·开发语言
我是海飞13 小时前
杰理 AC792N WebSocket 客户端例程使用测试教程
c语言·python·单片机·websocket·网络协议·嵌入式·杰理
项目題供诗13 小时前
C语言基础(三)
c语言·c++
码农水水14 小时前
中国电网Java面试被问:流批一体架构的实现和状态管理
java·c语言·开发语言·面试·职场和发展·架构·kafka
宵时待雨15 小时前
数据结构(初阶)笔记归纳2:顺序表的实现
c语言·数据结构·笔记·算法
小鱼233315 小时前
STM32中的中断机制与应用
c语言·stm32·单片机·嵌入式硬件·mcu
阿华hhh15 小时前
单片机day1
c语言·单片机·嵌入式硬件
我还可以再学点15 小时前
C语言常见函数
c语言·开发语言