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

相关推荐
RuoZoe1 天前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
祈安_5 天前
C语言内存函数
c语言·后端
norlan_jame6 天前
C-PHY与D-PHY差异
c语言·开发语言
czy87874756 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
m0_531237176 天前
C语言-数组练习进阶
c语言·开发语言·算法
Z9fish6 天前
sse哈工大C语言编程练习23
c语言·数据结构·算法
代码无bug抓狂人6 天前
C语言之单词方阵——深搜(很好的深搜例题)
c语言·开发语言·算法·深度优先
CodeJourney_J7 天前
从“Hello World“ 开始 C++
c语言·c++·学习
枫叶丹47 天前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
with-the-flow7 天前
从数学底层的底层原理来讲 random 的函数是怎么实现的
c语言·python·算法