2024-02-29 作业

本文介绍了如何在C语言中使用链表结构存储数据,然后通过fprintf将数据写入文件,以及使用fscanf从文件中读取数据并重新插入链表。主要涉及链表操作和文件I/O函数的应用。
摘要由CSDN通过智能技术生成
作业要求:

编写链表,链表里面随便搞点数据

使用 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
运行截图:
链表->w_file

r_file->链表

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值