在读取文件

时间:2015-11-28 12:16:11

标签: c while-loop realloc

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

这是功能

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分配固定金额,这可行,但是如果数据增加则不会。所以我试图让代码适应读取的数据量。

1 个答案:

答案 0 :(得分:2)

首先,让我告诉你

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 中使用新尺寸时,您必须维护并更新包含尺寸的单独计数器。像

这样的东西
Input: 451467
Output: 144567

应该为你做好工作。