编写链表,链表里面随便搞点数据 使用 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;
}
思维导图