读取文件时使用 realloc()

Using realloc() while reading file

每次 while 循环读取一组数据时,我正在尝试使用 realloc 为我的数组分配更多内存。

这是函数

void loadStats(Database *db){
  FILE *file = fopen("stats.txt", "r");
  int i = 0;
  while (fscanf(file,"%s %d/%d %d.%d %s - %s %d - %d %f", 
    &db[i].dayname, &db[i].day, &db[i].month, &db[i].hour, &db[i].minute,
    &db[i].hometeam, &db[i].awayteam, &db[i].homescore, &db[i].awayscore, &db[i].spectators) != EOF){
    db[i].spectators = db[i].spectators * 1000;
    i++;
    db = realloc(db, sizeof(db) + sizeof(Database));
  }
  fclose(file);
}

这是我正在尝试读取的文件:stats.txt

#include <stdio.h>
#include <stdlib.h>

typedef struct{
  char dayname[3];
  int day;
  int month;
  int hour;
  int minute;
  char hometeam[3];
  char awayteam[3];
  int homescore;
  int awayscore;
  float spectators;
} Database;

void loadStats(Database *db);
void printStats(Database *db);

int main(){
  Database *db = malloc(sizeof(Database));
  loadStats(db);
  printStats(db);
  return 0;
}

void loadStats(Database *db){
  FILE *file = fopen("stats.txt", "r");
  int i = 0;
  while (fscanf(file,"%s %d/%d %d.%d %s - %s %d - %d %f", 
    &db[i].dayname, &db[i].day, &db[i].month, &db[i].hour, &db[i].minute,
    &db[i].hometeam, &db[i].awayteam, &db[i].homescore, &db[i].awayscore, &db[i].spectators) != EOF){
    db[i].spectators = db[i].spectators * 1000;
    i++;
    db = realloc(db, sizeof(db) + sizeof(Database));
  }
  fclose(file);
}

void printStats(Database *db){
    int i;
    printf("Enter array number.\n");
    scanf("%d", &i);
    printf("db[%d].dayname = %s\ndb[%d].day = %d\ndb[%d].month = %d\ndb[%d].hour = %d\ndb[%d].minute = %d\n"
           "db[%d].hometeam = %s\ndb[%d].awayteam = %s\ndb[%d].homescore = %d\ndb[%d].awayscore = %d\ndb[%d].spectators = %f\n\n", 
            i, db[i].dayname, i, db[i].day, i, db[i].month, i, db[i].hour, i, db[i].minute,
            i, db[i].hometeam, i, db[i].awayteam, i, db[i].homescore, i, db[i].awayscore, i, db[i].spectators);
}

编辑:问题是这会崩溃,我试过不使用 realloc,只是用 malloc 分配一个固定的数量,这是可行的,但是如果数据增加,它就不会。所以我试图让代码适应读取的数据量。

首先告诉你

 db = realloc(db, sizeof(db) + sizeof(Database));

是一种非常糟糕的编码方式,万一 realloc() 失败,您最终也会丢失实际的指针。完成任务的更好方法是(伪代码)

Database * temp = NULL;
temp = realloc(db, sizeof(db) + sizeof(Database));
if (temp)
  db = temp;

也就是说,db 作为一个指针,sizeof(db) 将始终为您提供指针的大小,而不是分配给它的内存量。在 realloc() 中使用新尺寸时,您必须维护和更新一个单独的计数器来保存尺寸。像

 realloc(db, counter * sizeof(Database));  //counter is updated after every allocation

应该为您完成这项工作。