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

相关推荐
小师兄吃牛肉3 分钟前
C语言篇:内联函数
c语言·开发语言
白山编程大哥36 分钟前
C语言篇:语法进阶
c语言·数据结构·算法
Logic1011 小时前
C语言/数据结构动态规划题解:爬楼梯(含坏台阶)——避开障碍物的路径计数
c语言·数据结构·动态规划·时间复杂度·空间复杂度·算法题·爬楼梯
山下梅子酒2252 小时前
洛谷-入门-B2081
c语言
wuminyu2 小时前
Virtual Thread重投递至ForkJoinPool任务队列过程解析
java·linux·c语言·jvm·c++
Navigator_Z3 小时前
LeetCode //C - 1281. Subtract the Product and Sum of Digits of an Integer
c语言·算法·leetcode
iCxhust3 小时前
51单片机电力载波应用开发(七)广播通讯
c语言·开发语言·单片机·嵌入式硬件·51单片机
Hi202402173 小时前
同一个 NMS 算子,两种语言实现:CUDA C 与 Rust 生成 LLVM IR 和 Vortex 汇编的差异
c语言·汇编·rust·gpgpu·vortex·cudac
lhbweilai4 小时前
深挖FreeRTOS内核实现(二)
c语言·汇编·stm32·单片机
杨丰玮4184 小时前
C语言核心语法
java·c语言·开发语言·学习方法