为什么fgets函数在使用malloc()时没有以NULL指针结尾?

时间:2014-11-11 09:35:54

标签: c malloc fgets

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct island
{
    char *name;
    char *opens;
    char *closes;
    struct island *next;
} island ;

island* create(char *name){

    island *i = malloc(sizeof(island));
    i->name =strdup (name);
    i->opens ="09:00";
    i->closes ="17:00";
    i->next = NULL;
    return i;
}

void display(island *start){
        island *i = start;
        for (; i != NULL ; i = i->next)
            printf("Name: %s open: %s-%s\n",i->name,i->opens,i->closes);
}
void release(island *start){
        island *i = start;
        island *next = NULL;
        for (; i != NULL; i = next) {
            next =i->next;
            free(i->name);
            free(i);
        }
}


int main(){
    freopen("in.txt","r",stdin);
    char name[80];

    island *start = NULL;
    island *i = NULL;
    island *next = NULL;

    for(;fgets(name, 80, stdin)!=NULL; i =next) {
        next = create(name);
        if (start == NULL)
            start =next;
        if (i != NULL)
            i->next= next;
    }
    display(start);
    release(start);

    //display(p_island0);
    //display(&amity);
    return 0;
}

在我的代码中,它应该返回一个名称列表,其中包含相应的值,即字符串文字。我没有得到的是,在我的输出结束时,我得到一个空白的额外名称字段。我使用了fgets并用NULL调节它。但它仍在计算一个空格作为输入。我知道fgets在出错时返回NULL,或者在没有读取任何字符的情况下发生文件结束但在我的情况下它仍然没有在它获得NULL时终止。为什么是这样?我已经给出了我的输入文件和相应的输出。

这是我在代码中使用的输入文件&#34; in.txt&#34;

Atlantis
Santa
Barbara 
Modi
Ludio

这是我的输出。

Name: atlantis
open: 09:00-17:00
Name: santa
open: 09:00-17:00
Name: Barbara 
open: 09:00-17:00
Name: Modi
open: 09:00-17:00
Name: Ludio
open: 09:00-17:00
Name: 
open: 09:00-17:00

0 个答案:

没有答案