
2个回答
展开全部
//很简单,给你个单链表的例子,首先定义链表成员的结构体
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移动到最后一个节点
p->next = new;//p的下一个节点为new
new->next = NULL;//new的下一个节点为空
return head;
}
//这样这个函数就完成了,你可以写个主函数,定义一个头节点,试下
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移动到最后一个节点
p->next = new;//p的下一个节点为new
new->next = NULL;//new的下一个节点为空
return head;
}
//这样这个函数就完成了,你可以写个主函数,定义一个头节点,试下
参考资料: http://zhidao.baidu.com/question/100331421.html?si=1
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询