2021年1月23日星期六

C loading data from txt file into a linked list

I want to make a program that would load data from txt file and put it into a linked list then print that linked list out. It seems to work but it also prints out some junk too. I'm quite new to linked lists so it's probably some obvious mistake. I would appreciate if someone told how to fix it, thanks in advance.

That's what inside my txt file:

FORD    FIESTA  2010    1.6  OPEL    ASTRA   2005    1.4  

And that's what my program prints out:

FORD    FIESTA  2010    1.6  OPEL    ASTRA   2005    1.4  ­iŁ     ;C:\Windows;C:\Windows\System32\      1251983754      132.41  

And here's my code:

#include <stdio.h>  #include <stdlib.h>  #include <string.h>    typedef struct Cars  {      char brand[30], model[30];      int year;      float engine;      struct Cars *next;  } Cars_t;    void load_cars(Cars_t *head, char  file_name[30])  {      Cars_t *temp = head;        FILE *baza = fopen(file_name, "r");      if(baza!=NULL)      {          while(fscanf(baza, "%s%s%d%f", temp->brand, temp->model, &(temp->year), &(temp->engine)) == 4)          {                  temp->next=malloc(sizeof(Cars_t));                  temp=temp->next;          }          temp->next=NULL;      }      fclose(baza);  }    void print_list(Cars_t *head)  {      Cars_t *current = head;        while (current != NULL)      {          printf("%s\t%s\t%d\t%.2f\n", current->brand, current->model, current->year, current->engine);          current = current->next;      }  }    int main()  {      Cars_t *head = malloc(sizeof(Cars_t));      load_cars(head, "baza.txt");      print_list(head);        return 0;  }  
https://stackoverflow.com/questions/65865975/c-loading-data-from-txt-file-into-a-linked-list January 24, 2021 at 08:23AM

没有评论:

发表评论