Reputation: 23
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;
}
Upvotes: 2
Views: 493
Reputation: 493
You read 2 structs and alloc 3 times! First in main for head, then twice when you sucessfuly read from file. So your last alloc make no sense. I also add some security checks for your code but you only need to pay atention to lines comented with // <---- Special atention here!
Btw this example is not the best aproach i just did a fast fix for you to understand where is the problem.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Cars Cars_t, *pCars_t;
struct Cars
{
char brand[30], model[30];
int year;
float engine;
pCars_t next;
};
void load_cars(Cars_t *head, char file_name[30])
{
Cars_t *temp = head;
Cars_t *previous = NULL; // <---- Special atention here!
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));
if(temp->next == NULL)
{
fprintf(stderr, "Allocation error!\n");
exit(1);
}
previous = temp; // <---- Special atention here!
temp=temp->next;
}
temp->next=NULL;
free(previous->next); // <---- Special atention here!
previous->next=NULL; // <---- Special atention here!
}
else
{
fprintf(stderr, "File problem!");
return;
}
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()
{
pCars_t head = malloc(sizeof(Cars_t));
if(head == NULL)
{
fprintf(stderr, "Allocation error!\n");
return 1;
}
load_cars(head, "baza.txt");
print_list(head);
return 0;
}
Upvotes: 1