【发布时间】:2016-05-24 02:08:58
【问题描述】:
所以,我必须从文件输入中打印一个链接列表,我已经设法开始工作了:
#include <stdio.h>
#include <stdlib.h>
typedef struct Vehicle{
int option;
char make [30];
char model[30];
int car_manufacture_date;
float maximum_velocity;
float mass;
int seats;
struct Vehicle *next;//linked list node
} vehicle_t;
int main (){
FILE* fp;
fp = fopen("vehicles.crash.txt", "r");
vehicle_t* first_car = malloc(sizeof(vehicle_t));
if (first_car == NULL){
printf("Error. Failed to allocate memory to first_car\n");
exit(1);
}
vehicle_t* current_vehicle = malloc(sizeof(vehicle_t));
if (current_vehicle == NULL){
printf("Error. Failed to allocate memory to current_vehicle\n");
exit(1);
}
vehicle_t* new_vehicle = malloc(sizeof(vehicle_t));
if (new_vehicle == NULL){
printf("Error. Failed to allocate memory to new_vehicle\n");
exit(1);
}
printf("GOOD1\n");
current_vehicle = first_car;
new_vehicle = first_car;
printf("GOOD2\n");
//Loading vehicles from file to linked list
if (fp != NULL)
{
printf("GOOD3\n");
while (fscanf(fp,"%d %s %s %d %f %f %d", &new_vehicle->option, new_vehicle->make, new_vehicle->model, &new_vehicle->car_manufacture_date,
&new_vehicle->maximum_velocity, &new_vehicle->mass, &new_vehicle->seats) != EOF)
{
printf("GOOD4\n");
current_vehicle->next = new_vehicle;
current_vehicle = current_vehicle->next;
new_vehicle = malloc(sizeof(vehicle_t));
if (first_car == NULL){
printf("Error. Failed to allocate memory\n");
new_vehicle->next=NULL;
exit(1);
}
printf("GOOD5\n");
}
close(fp);
printf("Input completed\n");
}
else
printf("Error! couldn't find file\n");
current_vehicle = first_car;
while (current_vehicle != NULL)
{
printf("Option: %d\tMake: %s\tModel: %s\tManufactured: %d\tMax Velocity: %.2f\tMass: %.2f\tSeats: %d\n",
current_vehicle->option, current_vehicle->make, current_vehicle->model, current_vehicle->car_manufacture_date,
current_vehicle->maximum_velocity, current_vehicle->mass, current_vehicle->seats);
new_vehicle = current_vehicle->next;
current_vehicle = current_vehicle->next;
};
printf("Printing completed");
return 0;
}
在打印出最后一个文件项之前一切正常,之后程序崩溃。从我在其他帖子中看到的情况来看,while 循环与它们都匹配。
打印出来的"GOOD" 语句只是检查点
文件中的文本格式为:1 Toyota Camry 2010 200.0 1100.0 5
【问题讨论】:
-
您在调试器下运行程序了吗?
-
输入循环后需要
current_vehicle->next = NULL;。还有很多内存泄漏。 -
为什么会有前 3 个 malloc?我原以为您只需要为拥有真实数据的事物分配内存。
-
fclose应该被调用而不是close,其参数是文件描述符而不是FILE指针。 -
启用编译器警告,你的
close()甚至没有在你的代码中声明。它调用未定义的行为,因为它将FILE *视为int。
标签: c file linked-list