我目前正在尝试填充像这样的结构
typedef struct
{
int year;
int month;
int day;
int hour;
int minute;
} tDateTime;
typedef struct sFlight
{
char code[MAX_NAME_LENGTH];
char arrival[MAX_NAME_LENGTH];
char departure[MAX_NAME_LENGTH];
int availableSeats;
tDateTime dateTime;
struct sFlight * nextFlight;
} tFlight;
从txt文件中读取。这就是我目前正在做的事情
void ops_loadFlightsInformation(tFlight * firstFlight)
{
// Open the file with r to only read
FILE *file = fopen(OPS_FLIGHTS_FILE, "r");
// If file is not open return
if(file == NULL) {
return;
}
tFlight currentFlight;
// Loop until there are no flights
while(next != 0) {
strcpy(currentFlight.code, helpers_scanFromFile(file, MAX_NAME_LENGTH));
strcpy(currentFlight.departure, helpers_scanFromFile(file, MAX_NAME_LENGTH));
strcpy(currentFlight.arrival, helpers_scanFromFile(file, MAX_NAME_LENGTH));
fscanf(file, "%d\n", ¤tFlight.availableSeats);
fscanf(file, "%d/%02d/%02d %02d:%02d\n", ¤tFlight.dateTime.year, ¤tFlight.dateTime.month, ¤tFlight.dateTime.day, ¤tFlight.dateTime.hour, ¤tFlight.dateTime.minute);
fscanf(file, "%d\n", &next);
printf("%s \n", currentFlight.code);
}
printf("%s \n", firstFlight->code);
// Close the file handle
fclose(file);
}
我无法思考如何填充while循环中的struct指针。我尝试了不同的方法,但我总是以
结束warning: X may be used uninitialized in this function
或者只是反复编辑同一个指针,只编辑第一个元素。循环工作正常currentFlight正确填充但我不知道如何将其转换为firstFlight结构和 - > nextFlight指针
答案 0 :(得分:1)
您想阅读航班并将其列入清单。因此,在阅读下一个航班之前,请分配一段新内存并将其放入next
。然后使用指针表示法来解决成员:
void ops_loadFlightsInformation(tFlight * firstFlight)
{
// Open the file with r to only read
FILE *file = fopen(OPS_FLIGHTS_FILE, "r");
// If file is not open return
if(file == NULL) {
return;
}
tFlight *currentFlight = firstFlight;
// Loop until there are no flights
while(!feof(file)) {
currentFlight->next= malloc(sizeof(tFlight));
currentFlight= currentFlight->next;
strcpy(currentFlight->code, helpers_scanFromFile(file, MAX_NAME_LENGTH));
strcpy(currentFlight->departure, helpers_scanFromFile(file, MAX_NAME_LENGTH));
strcpy(currentFlight->arrival, helpers_scanFromFile(file, MAX_NAME_LENGTH));
fscanf(file, "%d\n", ¤tFlight->availableSeats);
fscanf(file, "%d/%02d/%02d %02d:%02d\n", ¤tFlight->dateTime.year, ¤tFlight->dateTime.month, ¤tFlight->dateTime.day, ¤tFlight->dateTime.hour, ¤tFlight->dateTime.minute);
//fscanf(file, "%d\n", &next); // what is this?????
printf("%s \n", currentFlight->code);
}
printf("%s \n", firstFlight->code);
// Close the file handle
fclose(file);
}
(注意:应添加scanf
上的检查代码和malloc
。假设您的帮助程序正确并且始终读取字符串。假设文件至少包含一个航班。)