作业要求:
编写链表,链表里面随便搞点数据
使用 fprintf 将链表中所有的数据,保存到文件中
使用 fscanf 读取文件中的数据,写入链表中
运行代码:
main.c
#include "link.h"
int main(int argc, const char *argv[])
{
link_p H = creat_head();
link_p H1 = creat_head();
FILE *wfp=fopen("./w_file","w");
FILE *rfp=fopen("./r_file","r");
if(wfp==NULL){
printf("创建失败\n");
return 1;
}
insert_tail(H,1);
insert_tail(H,2);
insert_tail(H,3);
insert_tail(H,4);
insert_tail(H,5);
insert_tail(H,6);
read_link(wfp,H);
write_link(rfp,H1);
print(H1);
fclose(wfp);
fclose(rfp);
free_p(&H);
free_p(&H1);
return 0;
}
link.c
#include "link.h"
link_p creat_head()
{
link_p H = (link_p)malloc(sizeof(link_list));
if(NULL==H){
return NULL;
}
H->next=NULL;
H->len=0;
return H;
}
link_p creat_node(datatype data)
{
link_p new = (link_p)malloc(sizeof(link_list));
if(new==NULL){
return NULL;
}
new->data=data;
return new;
}
void insert_tail(link_p H,datatype data)
{
if(NULL==H){
return;
}
link_p new = creat_node(data);
link_p p = H;
while(1){
if(p->next==NULL){break;}
p=p->next;
}
new->next=p->next;
p->next=new;
H->len++;
}
void read_link(FILE *wfp,link_p H)
{
if(wfp==NULL||H==NULL){printf("入参失败\n");return;}
link_p p= H->next;
while(1){
if(p==NULL){break;}
fprintf(wfp,"%d ",p->data);
p=p->next;
}
}
void write_link(FILE *rfp,link_p H1)
{
if(rfp==NULL||H1==NULL){
printf("文件入参失败\n");
return;
}
int a=0;
while(1){
int res=fscanf(rfp,"%d",&a);
if(res!=1){break;}
insert_tail(H1,a);
}
}
void print(link_p H)
{
link_p p = H->next;
while(1){
if(NULL==p){break;}
printf("%d->",p->data);
p=p->next;
}
printf("NULL\n");
}
void free_p(link_p *H)
{
if(*H==NULL||H==NULL){
printf("入参失败\n");
return;
}
link_p p = *H;
link_p del = *H;
while(1){
if(p==NULL){return;}
del = p;
p=p->next;
free(del);
del=NULL;
}
*H=NULL;
}
link.h
#ifndef __LINK_H__
#define __LINK_H__
#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 creat_head();
link_p creat_node(datatype data);
void insert_tail(link_p H,datatype data);
void read_link(FILE *wfp,link_p H);
void print(link_p H);
void write_link(FILE *rfp,link_p H1);
void free_p(link_p *H);
#endif