关于文件读取到链表

你今晚必睡不着觉 2018-01-06 09:36:07
设我有一个文件,里面有若干个单词,创建一个链表存储这些单词。但是在运行的时候出错……不知道哪里错了

Word* CreativeLink(FILE* p){

Word* head = NULL;
Word* current = NULL;
//Word* next = NULL;
Word* last = NULL;
do
{
current = (Word*)malloc(sizeof(Word));
if (head == NULL)
head = current;
if (last != NULL)
last->next = current;
if (fgets(current->word,MaxLenth,p) == EOF) break;

current->next = NULL;
last = current;
} while (true);
return head;
}

int main(){
FILE* p;
Word* head;
if((p = fopen("test.txt","r"))==NULL)
return 0;
head = CreativeLink(p);
fclose(p);
return 0;
}
错误显示我Expression: stream.valid()
...全文
355 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
自信男孩 2018-01-07
  • 打赏
  • 举报
回复
Word* CreativeLink(FILE* p)
{

	Word* head = NULL;
	Word* current = NULL;
	//Word* next = NULL;
	Word* last = NULL;
	do
	{
		current = (Word*)malloc(sizeof(Word));
		if (head == NULL)
			head = current;
		if (last != NULL)
			last->next = current;
		if (fgets(current->word, MaxLenth, p) == NULL) 
			break;

		current->next = NULL;
		last = current;
	} while (true);

	last->next = NULL;
	free(current);    /* last malloc not used */

	return head;
}

int main(){
	FILE* p;
	Word* head;
	if((p = fopen("test.txt","r"))==NULL)
		return 0;
	head = CreativeLink(p);
	fclose(p);
	return 0;
}
参考一下吧 问题1:fgets遇到EOF返回NULL,因此判断时应用NULL判断; 问题2:current最后一个节点没有使用,因此需要free掉,并保证last->next为NULL;
  • 打赏
  • 举报
回复
引用 1 楼 hefashion0190 的回复:
fgets文件结尾并不是由返回值等于EOF来判断
RETURN VALUES
     Upon successful completion, fgets() and gets() return a pointer to the string.
     If end-of-file occurs before any characters are read, they return NULL and the
     buffer contents remain unchanged.  If an error occurs, they return NULL and the
     buffer contents are indeterminate.  The fgets() and gets() functions do not dis-
     tinguish between end-of-file and error, and callers must use feof(3) and
     ferror(3) to determine which occurred.
但是我改成fscanf(p,"%s",current->word)!=EOF 也会报错,然后我又把循环条件放在while里面:while(!feof(p))错误提示我public_stream != nullptr
  • 打赏
  • 举报
回复
这个问题我已经解决了,但是不知道原理。 原先我实在主函数打开文件,并把该文件指针作为参数传向创建链表的函数中,但这样做出错不能运行。 但是我后来把打开文件的操作放在创建链表的函数中,发现可以正常运行。 这是为什么啊?按道理在主函数打开文件后指针传过去应该没有错误的啊……求解……
FoolCarpe 2018-01-06
  • 打赏
  • 举报
回复
fgets文件结尾并不是由返回值等于EOF来判断
RETURN VALUES
     Upon successful completion, fgets() and gets() return a pointer to the string.
     If end-of-file occurs before any characters are read, they return NULL and the
     buffer contents remain unchanged.  If an error occurs, they return NULL and the
     buffer contents are indeterminate.  The fgets() and gets() functions do not dis-
     tinguish between end-of-file and error, and callers must use feof(3) and
     ferror(3) to determine which occurred.

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧