head.h
#ifndef __HEAD_H__
#define __HEAD_H__
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<pthread.h>
#include<sys/wait.h>
#include<signal.h>
typedef char datatype[128];
typedef struct node{
union{
int len;
datatype data;
};
struct node* next;
}*linklist;
linklist create_head();
linklist create_linknode(datatype key);
int insert(linklist L,datatype key);
int out_file(FILE*fp_w,linklist L);
void mfree(linklist*L);
#endif
fun1.c
#include"head.h"
linklist create_head(){
linklist L=(linklist)malloc(sizeof(struct node));
if(NULL==L){
printf("申请空间失败\n");
return NULL;
}
L->len=0;
L->next=NULL;
return L;
}
linklist create_linknode(datatype key){
linklist p=(linklist)malloc(sizeof(struct node));
if(NULL==p){
printf("申请空间失败\n");
return NULL;
}
strcpy(p->data,key);
p->next=NULL;
return p;
}
int insert(linklist L,datatype key){
if(NULL==L){
printf("传参失败\n");
return -1;
}
linklist f=L;
while(f->next!=NULL){
f=f->next;
}
linklist p=create_linknode(key);
if(p==NULL){
printf("创建节点失败\n");
return -1;
}
f->next=p;
(L->len)++;
return 0;
}
int out_file(FILE*fp_w,linklist L){
linklist p=L->next;
for(int i=0;i<L->len;i++){
if(fprintf(fp_w,"%s",p->data)<0){
perror("fprintf");
return -1;
}
p=p->next;
}
return 0;
}
void mfree(linklist*L){
if(NULL==L||NULL==*L){
printf("传参无效\n");
return ;
}
linklist p=*L;
while(p==NULL){
linklist pn=p;
free(p);
p=pn->next;
}
*L=NULL;
}
main.c
#include"head.h"
int main(int argc, const char *argv[])
{
static char buf[128];
FILE*fp_r=fopen("../standard_io/cpy_f.c","r");
if(fp_r==NULL){
perror("fopen");
return -1;
}
FILE*fp_w=fopen("./1.c","w");
if(fp_w==NULL){
perror("fopen");
return -1;
}
linklist L=create_head();
while(1){
if(fscanf(fp_r,"%s",buf)==-1){
break;
}
insert(L,buf);
}
printf("文件读取完成\n");
out_file(fp_w,L);
printf("文件写入完成\n");
mfree(&L);
fclose(fp_r);
fclose(fp_w);
return 0;
}