创建一个链表,用标准io读取文件数据插入链表,读取链表数据插入另一个文件

head.h

cs 复制代码
#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

cs 复制代码
#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

cs 复制代码
#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;
}
相关推荐
郝学胜-神的一滴11 分钟前
Effective STL 条款09:慎重选择删除元素的方法
开发语言·网络·数据结构·c++·算法·stl
Johny_Zhao28 分钟前
Keepalived与Nginx架构选型
linux·nginx·信息安全·云计算·apache·shell·yum源·keepalive·系统运维
FlightYe3 小时前
linux系统编程(二十一):C 语言常见坑
android·linux·运维·服务器·c语言·音视频
by209994 小时前
Linux 文件描述符与重定向
linux·服务器
橙橙笔记4 小时前
Linux基础与命令的学习
linux·运维·服务器·shell
无奈笑天下4 小时前
银河麒麟桌面操作系统【命令行配置文件与图片搜索功能】操作方法
linux·运维·服务器
geovindu4 小时前
python:Logistic Regression
开发语言·后端·python·算法
番茄味城市甜菜5 小时前
二叉树刷题(C语言)
c语言·开发语言
飞花漫卷,情随岁迁5 小时前
网络数据包转发与内核机制:小白概念科普
linux·运维·网络·数据库·mysql·oracle·智能路由器
geovindu5 小时前
python: Random Forest
开发语言·后端·python·算法·随机森林