作业: 编写链表,链表里面随便搞点数据 使用 fprintf 将链表中所有的数据,保存到文件中 使用 fscanf 读取文件中的数据,写入链表中
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
//链表结构体定义
typedef struct link_list
{
union
{
int data;
int len;
};
struct link_list *next;
}link_list,*link_p;
//创建头结点
link_p creat_head()
{
link_p H = (link_p)malloc(sizeof(link_list));
if(H==NULL){
printf("申请空间失败\n");
return NULL;
}
H->len = 0;
H->next = NULL;
return H;
}
//创建新结点
link_p new_nod(int data)
{
link_p new = (link_p)malloc(sizeof(link_list));
if(new==NULL){
printf("申请空间失败\n");
return NULL;
}
new->data = data;
return new;
}
//尾插
void insert_tail(link_p L,int data)
{
if(L==NULL){
printf("入参失败\n");
return;
}
link_p p = L;
link_p new = new_nod(data);
while(p->next!=NULL){
p = p->next;
}
new->next = p->next;
p->next = new;
}
//遍历
void out_put(link_p L)
{
link_p p = L->next;
while(p!=NULL){
printf("%d->",p->data);
p=p->next;
}
printf("NULL");
putchar(10);
}
int main(int argc, const char *argv[])
{
link_p L = creat_head();
insert_tail(L,10);
insert_tail(L,20);
insert_tail(L,30);
insert_tail(L,40);
//out_put(L);
link_p p = L->next;
FILE *wfp = fopen("link.txt","w");
if(wfp==NULL){
return 1;
}
while(p!=NULL){
int ret = fprintf(wfp,"%d\n",p->data);
p=p->next;
}
fclose(wfp);
FILE *rfp = fopen("link.txt","r");
link_p L2 = creat_head();
int data=0;
while(1){
int ret = fscanf(rfp,"%d",&data);
printf("%d\n",data);
if(ret!=1){break;}
insert_tail(L2,data);
}
out_put(L2);
fclose(rfp);
return 0;
}