main.c
#include "fun.h"
int main(int argc, const char *argv[])
{
link_p link1 = creat_head();
link_p link2 = creat_head();
insert_head(link1,11);
insert_head(link1,22);
insert_head(link1,33);
insert_head(link1,44);
insert_head(link1,55);
insert_head(link1,66);
insert_head(link1,77);
insert_head(link1,88);
insert_head(link1,99);
printf("link1:");
out_put(link1);
FILE *fp1=fopen("link1.txt","w");
if(NULL == fp1){
printf("文件打开失败\n");
return -1;
}
while(1){
fprintf(fp1,"%d\n",link1->next->data);
link1=link1->next;
if(link1->next == NULL){
break;
}
}
//如果在一个文件里里面操作
//fclose(fp1);
//fp1=fopen("link1.txt","r");
FILE *fp2 = fopen("link2.txt","r");
if(NULL == fp2){
printf("文件打开失败\n");
return -1;
}
int data=0;
link_p pp=link2;
while(1){
int ret=fscanf(fp2,"%d",&data);
if(ret != 1){
break;
}
link_p node=creat_node(data);
node->next=pp->next;
pp->next=node;
}
printf("link2:");
out_put(link2);
fclose(fp1);
fclose(fp2);
return 0;
}
fun.c
#include "fun.h"
//creat head
link_p creat_head(){
link_p head = (link_p)malloc(sizeof(link1));
if(NULL==head){
printf("error1\n");
return NULL;
}
head->len=0;
head->next=NULL;
return head;
}
//creat node
link_p creat_node(datatype data){
link_p node = (link_p)malloc(sizeof(link1));
if(NULL == node){
printf("error2\n");
return NULL;
}
node->data=data;
node->next=NULL;
return node;
}
//insert head
void insert_head(link_p L,datatype data){
if(NULL == L){
printf("error3\n");
return;
}
link_p p=creat_node(data);
p->next=L->next;
L->next=p;
return;
}
//link out put
void out_put(link_p L){
if(NULL == L){
printf("error4\n");
return;
}
link_p p=L->next;
while(p!=NULL){
printf("%d->",p->data);
p=p->next;
}
printf("NULL\n");
return;
}
fun.h
#ifndef __FUN_H__
#define __FUN_H__
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
typedef int datatype;
typedef struct link{
union{
datatype data;
int len;
};
struct link *next;
}link1,*link_p;
link_p creat_head();
link_p creat_node(datatype data);
void insert_head(link_p L,datatype data);
void out_put(link_p L);
#endif
现象:
思维导图