C将文本文件中的数据加载到链表中



我想做一个程序,将加载数据从txt文件,并把它到一个链表,然后打印链表出来。它似乎工作,但它也打印出一些垃圾。我对链表很陌生,所以这可能是一些明显的错误。如果有人告诉我如何修理它,我会很感激,提前谢谢。

这就是我的txt文件里面的内容:

FORD    FIESTA  2010    1.6
OPEL    ASTRA   2005    1.4

这就是我的程序打印出来的内容:

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

下面是我的代码:

#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("%st%st%dt%.2fn", 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;
}

读取2个结构体并分配3次!首先在main中用于head,然后在成功地从文件中读取时执行两次。所以你上次的分配没有意义。我还为你的代码添加了一些安全检查,但你只需要注意用// <---- Special atention here!

注释的行。顺便说一句,这个例子不是最好的方法,我只是做了一个快速修复,让你了解问题在哪里。

#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("%st%st%dt%.2fn", 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;
}

相关内容

  • 没有找到相关文章

最新更新