c语言如何从文件读入,并存放在链表中
来源:百度知道 编辑:UC知道 时间:2024/05/24 13:01:22
//举个单链表的例子,首先定义链表成员的结构体
struct filetext{char buf[BUFSIZE];
struct filetext *next;};
//读取文件,并插入进链表的函数,filename为要读取的文件名,head为链表的头节点,函数返回插入新节点后链表的头节点
struct filetext * readfile(char * filename,struct filetext * head)
{ struct filetext * new = (struct filetext *)malloc(sizeof(struct filetext));//定义一个新成员,并给它分配空间
FILE * fp;//读取文件的文件流
struct filetext * p =head;//定义一个p,用来寻找链表中最后一个节点
if((fp=(fopen(filename,"r+")))==NULL)
{//如果打开文件失败,返回head,并提示
printf("open file failure");
return head; }
//然后开始读取文件,放到new的buf中
if(fread(new->buf,BUFSIZE,1,fp)<1)
{ //如果读取失败,提示,并返回head
printf("read file failure");
return head; }
fclose(fp);
//文件读取完后,进行链表操作
if(!head)//如果传进来的head是个空指针,那么新指针就作为头节点返回
{ new->next = NULL;
return new; }
while(p->next) p = p->next;//把p移动到最后一个节点