#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;
}
In my code it should return a list of names with their correspondent values which is string literals. what I am not getting is that at the end of my output i am getting an extra name field which is blank. I have used fgets and conditioned it with NULL. but still it is counting a blank space as an input. I know fgets returns NULL on error or when end of file occurs while no characters have been read but in my case it is still not terminated while it gets a NULL. why is this? i have given my input file and corresponding output.
This is my input file used in code as "in.txt"
Atlantis
Santa
Barbara
Modi
Ludio
This is my output.
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