我目前正在尝试填充这样的结构
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 循环上的结构指针。我尝试了不同的方法,但最终总是得到 p>
warning: X may be used uninitialized in this function
或者只是一遍又一遍地编辑同一个指针,因此只编辑第一个元素。循环工作正常 currentFlight 已正确填充,但我不知道如何将其转换为 firstFlight 结构和 ->nextFlight 指针
最佳答案
您想要读取航类并将其放入列表中。因此,在读取下一个航类之前,分配一 block 新的内存并将其放入 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
上的检查代码。假设您的助手是正确的并且始终读取字符串。假设文件至少包含一个航类。 )
关于C 指针算术填充结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40579915/