/* * func.c * * Created on: 2012-12-8 * Author: wzm */ #include"head.h" void Init(pList mylist) { mylist->size=0; mylist->head.next=NULL; mylist->head.s=NULL; } int Create(pList mylist) { pNode tmp=&mylist->head;//先保存一下头结点 int i=0; while(i<7)//创建多少个,就设置i为多少,不过也可以自动添加 { i++; pNode p=(pNode)malloc(sizeof(pNode));//构造空间 if(&mylist->head==NULL) { mylist->head=*p; p->s=NULL; mylist->size++; p->next=NULL; tmp=&mylist->head; } else { tmp->next=p;//在栈空间里面每一次调用原来创建的内容会被销毁,为了防止这个只能用堆空间里面的malloc来开辟空间,这个是会一直保存的, p->s=NULL;//将要放的那个元素 让所在原来位置的值的下一个节点所指向, mylist->size++; p->next=NULL;//指向尾节点 tmp=tmp->next;//让所在原来位置的值的下一个节点所指变成现在所在的节点,这就有利于下一次创建链表 } } printf("%d 个数\n",mylist->size); return mylist->size;//返回成功录入的元素的个数 } void FileToLink(char *s,pList mylist) { FILE *fp; char str[1024]; fp=fopen(s,"a+"); if(fp==NULL) { puts("文件不能打开"); return ; } pNode p=mylist->head.next; while(fgets(str,1024,fp)!=NULL&&p!=NULL) { if(p==NULL) { puts("??"); p=(pNode)malloc(sizeof(pNode)); mylist->size++; } p->s=(char *)malloc(sizeof(char)*1024); printf("---------%s\n",str); strcpy(p->s,str); printf("---------%s\n",p->s); p=p->next; } printf("size=%d\n",mylist->size); fclose(fp); } void Display(pList mylist) { pNode p=mylist->head.next; if(p==NULL) { puts("链表为空!"); return ; } else { while(p) { puts("---------------1111----------------"); printf("------------------------%s",p->s); p=p->next; } if(p==NULL) { puts("便历结束!"); } } }
/* * head.h * * Created on: 2012-12-8 * Author: wzm */ #include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct _D_Node { char *s; struct _D_Node *next; }Node,*pNode; typedef struct _D_List { unsigned size; struct _D_Node head; }List,*pList; void FileToLink(char *s,pList mylist); void Display(pList mylist); int Create(pList mylist);
file.txt文件 many soga what hahah yoyo zeaze lovemany 运行结果: 7 个数 ---------many ---------many ---------soga ---------soga ---------what ---------what ---------hahah ---------hahah ---------yoyo ---------yoyo ---------zeaze ---------zeaze ---------lovemany ---------lovemany size=7 ---------------1111---------------- ------------------------many ---------------1111---------------- ------------------------soga ---------------1111---------------- ------------------------what ---------------1111---------------- ------------------------hahah ---------------1111---------------- ------------------------yoyo ---------------1111---------------- ------------------------zeaze ---------------1111---------------- ------------------------lovemany便历结束!
将文件读取到链表里面
最新推荐文章于 2022-05-08 21:43:27 发布