sstefan
sstefan

Reputation: 395

Loading info from a file into a list in c

I'm writing a program which will read info from a file, line by line, and then load the info into a doubly linked list. The info is loaded as a structure called tvshow:

typedef struct tvshow{
    char name[20];
    int epNumber;
    int year;
    float duration;
    char country[3];
    char genre[20];
}tvshow;

typedef struct node{
    tvshow inf;
    struct node *next;
    struct node *prev;
}node;

void insert(node **, tvshow);
void print(node *);
FILE *safe_open(char *, char *);
void load(node **, FILE *);

int main(){
    node *head;
    head=NULL;

    FILE *in=safe_open("tvshows.txt", "r");

    load(&head, in);
    print(head);

    fclose(in);

    return 0;
    }

void insert(node **head, tvshow data){
    node *new=malloc(sizeof(node));
    new->inf=data;
    new->next=NULL;

    if (*head==NULL){
        *head=new;
        new->prev=NULL;
    }else{
        node *temp=*head;
        while (temp->next!=NULL){
        temp=temp->next;
     }
    temp->next=new;
    new->prev=temp;
    }
}

void print(node *head){
    while (head!=NULL){
        printf("%s %d %d %f %s %s\n", head->inf.name,head->inf.epNumber,head->inf.year, head->inf.duration,head->inf.country, head->inf.genre);
        head=head->next;
    }
}

FILE *safe_open(char *name, char *mode){
    FILE *fp=fopen(name, mode);

    if (fp==NULL){
        printf("failed to open");
        exit(1);
    }

    return fp;
}

void load(node **head, FILE *fp){
    tvshow temp;

    while (fscanf(fp, "%s %d %d %f %s %s", temp.name, &temp.epNumber,&temp.year, &temp.duration, temp.country, temp.genre)!=EOF){
        insert(head, temp);
    }
}

here is the example line from the .txt file: TheSopranos 86 1999 55 USA Drama

What is bothering me is that when I run the program, it prints the following:

TheSopranos 86 1999 55 USADrama Drama

Why USADrama? Where did it go wrong?

Upvotes: 1

Views: 220

Answers (1)

novice
novice

Reputation: 545

change char country[3] to char country[4] for the '\0' null character

Upvotes: 1

Related Questions