33,311
社区成员
发帖
与我相关
我的任务
分享
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;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.