I'm reading data from a file and need to have a dynamic array of structs based on how many lines are read from the file.
The file I am reading could have up to 5000 lines, and in theory I could just create an array of size 5000, but I see that as inefficient as some files could have only have 10 lines.
The file could hold 5000 participants, and I'd rather make a dynamic array than a fixed one.
My struct which holds all the necessary data members.
A possible solution could be finding number of lines inside text file beforehand, and allocating space for reading.
struct RiderInfo
{
char name[41];
int age;
char raceLength[2];
double startTime;
double mountainTime;
double finishTime;
int withdrawn;
};
// Allocate space for next element
void allocateParticipant(struct RiderInfo participantList[])
{
participantList = realloc(participantList, sizeof(struct RiderInfo));
}
// Read file
int readData(struct RiderInfo participantList[], const char filepath[])
{
// Declare Variables
int amount = 0, rValue = 0;
// Declare filepointer
FILE* fp = fopen(filepath, "r");
// Continue to loop while return of readfile is correct
while (rValue == 0)
{
allocateParticipant(participantList);
// Read one line file, rValue is the return (if return of 1 eof reached)
rValue = readFileRecord(fp, &participantList[amount]);
amount++;
}
return amount;
}
// Free memory
void freeMemory(struct RiderInfo participantList[])
{
free(participantList);
}
int main(void)
{
// Declare struct array to hold each participants values
struct RiderInfo participant[] = { 0 };
// Declare filename for data
const char datafile[] = "data.txt";
// Read data from file and save return in size
int size = readData(&participant, datafile);
// Output Data
for (i = 0; i < size; i++)
{
printParticipant(&participant[i], 0);
}
// Free all used memory before exit
freeMemory(&participant);
//Exit
return 0;