前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >c语言链表数据存入文件和读取文件

c语言链表数据存入文件和读取文件

作者头像
全栈程序员站长
发布2022-08-22 13:28:40
2.5K0
发布2022-08-22 13:28:40
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

近快一年没有接触c语言了,今天学妹问我了链表数据存如文件和读取文件到链表怎么实现,现在搞开发很少用文件,都是用数据库,在这儿我还是写一下简单的文件读取链表的操作。在c语言中,创建单链表需要使用到malloc函数动态申请内存;文件的读写需要首先使用fopen函数打开文件,然后使用fscanf,fgetc, fgets,fprintf,fputc,fputs等函数读写函数,最后读写完毕要使用fclose函数关闭函数。

下面的源程序展示了关于单链表如何从文件中读取数据和往文件里存入数据。

typedef struct node {

int data;

struct node *next;

}node;

//从文件中读取数据存入链表

node *createlink()

{

node *head =(node*)malloc(sizeof(node));

int t;

node *p;

node *q;

p=q=head;

FILE * r= fopen("input.txt","r");

if(r==NULL)

{

printf("打开文件失败!");

return NULL;

}

while(fscanf(r,"%d",&t)!=EOF)

{

q= (node*)malloc(sizeof(node));

q->data=t;

p->next=q;

p=q;

}

p->next=NULL;

return head;

}

//输出链表到屏幕和文件output.txt

void outlink(node *head)

{

node *p=head->next;

FILE *w =fopen("output.txt","w");

if(w==NULL)

{

printf("打开文件失败!");

return;

}

while(p)

{

//输出链表节点数据到屏幕

printf("%d ",p->data);

//输出链表节点数据到文件output.txt

fprintf(w,"%d ",p->data);

p=p->next;

}

printf("\n");

fprintf(w,"\n");

fclose(w);

return;

}

int main()

{

node *head;

int n,m;

head=createlink();

outlink(head);

system("pause");

return 0;

}

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/137216.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年5月5,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档