2.29IO进程线程

本文介绍了如何使用C语言实现链表,包括创建链表结构、插入节点、以及通过fprintf将链表数据保存到文件并用fscanf从文件读取数据重新插入链表的操作过程。
摘要由CSDN通过智能技术生成

 编写链表,链表里面随便搞点数据 使用 fprintf 将链表中所有的数据,保存到文件中 使用 fscanf 读取文件中的数据,写入链表中

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

typedef struct link_list
{
   	int data;
    struct link_list *next;
}lis,*linkp;

linkp create_head()
{
    linkp L = (linkp)malloc(sizeof(lis));
    if(L==NULL)
    {
        printf("空间申请失败\n");
        return NULL;
    }
    L->next=NULL;
    return L;
}
linkp create_node(int data)
{
    linkp new = (linkp)malloc(sizeof(lis));
    if(new==NULL)
    {
        printf("空间申请失败\n");
        return NULL;
    }
    new->data = data;
    return new;
}
void insert_head(linkp H,int data)
{
    if(H==NULL)
    {
        printf("入参为空,请检查\n");
        return;
    }
    linkp new = create_node(data);
    new->next = H->next;
    H->next = new;
}
void output(linkp H)
{
    if(H==NULL)
    {
        printf("入参为空,请检查\n");
        return;
    }
    linkp p = H->next;
    while(p!=NULL)
    {
        printf("%d\n",p->data);
        p = p->next;
    }
}
int save(linkp H)
{
	FILE* wfp = fopen("./save.txt","w");
	linkp t = H->next;
	if(wfp==NULL)
		return 1;
	int n=0;
	while(t)
	{
		fprintf(wfp,"%d\n",t->data);
		t=t->next;
		n++;
	}
	fclose(wfp);
	return n;
}
linkp reads(linkp H,int n)
{
	FILE* rfp = fopen("./save.txt","r");
	linkp t = H->next;
	if(rfp==NULL)
		return NULL; 
	linkp p1 = H;
	int a[n];
	int i=0;
	while(n)
	{
		fscanf(rfp,"%d\n",&a[i]);
		insert_head(p1,a[i]);
		n--;
		i++;
	}
	fclose(rfp);
	return p1;
}
int main(int argc, const char *argv[])
{
	linkp p = create_head();
	insert_head(p,12);
	insert_head(p,34);
	insert_head(p,56);
	insert_head(p,78);
	printf("头插写入链表\n");
	output(p);
	int n=save(p);
	printf("fprintf将数据写入save.txt文件后,fscanf读取文件数据,头插写入链表\n");
	output(reads(p,n));
	return 0;
}

思维导图

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值