Code:
match_t *readMatchStats(char *fileName) {
char *lineStart;
int arrayIndex;
int matchIndex;
double *ptr;
FILE *dataFile;
char *token;
char *line = alloca(sizeof(char) * READ_BUFFER_SIZE);
match_t *matchArray = xmalloc(sizeof(match_t) * 13);
dataFile = fopen(fileName, "r");
while (fgets(line, READ_BUFFER_SIZE, dataFile) != NULL) {
lineStart = strchr(line, ';');
lineStart = lineStart == NULL ? line : lineStart + 1;
charReplace(line, '#', '\0', 1);
if (!strlen(lineStart)) continue;
token = strtok(lineStart, " ");
for (matchIndex = 0; matchIndex < 3; matchIndex ++) {
if (!strIsFloat(token)) {
error(1, 0, "datafile parsing error -- expected float");
}
if (!matchIndex) ptr = &matchArray[arrayIndex].home;
else if (matchIndex == 1) ptr = &matchArray[arrayIndex].draw;
else ptr = &matchArray[arrayIndex].away;
*ptr = strtod(token, NULL);
token = strtok(NULL, " ");
}
arrayIndex ++;
}
fclose(dataFile);
return matchArray;
}
Code:
void test_readMatchStats() {
int c;
match_t *matchArray;
match_t facit[] = {
{0.11, 0.12, 0.13},
{0.21, 0.22, 0.23},
{0.31, 0.32, 0.33},
{0.41, 0.42, 0.43},
{0.51, 0.52, 0.53},
};
matchArray = readMatchStats("test.txt");
/*for (c = 0; c < 13; c ++) {
assert(facit[c].home == array[c].home);
assert(facit[c].draw == array[c].draw);
assert(facit[c].away == array[c].away);
}*/
}
EDIT: (I forgot...)
Code:
void *xmalloc(size_t size) {
void *ptr;
if ((ptr = malloc(size)) == NULL) error(1, errno, NULL);
return ptr;
}