I want to read from a file and create a dynamic array based on it (for using the qsort()) method on. I've got the following code to get the number of lines in the file (that meet a certain criteria, but don't know how to populate the individual elements of the array).
FILE* file = fopen("$filename", "r");
int count = 0; // Count num lines in the file
char buffer[50];
while(fgets(buffer, 50, file)) {
count++;
}
char** myArray;
myArray = malloc(count * sizeof(char*));
for (int i = 0; i < count; i++) {
myArray[i] = malloc(sizeof(char) * 51); // to include space for terminating character
}
// Re-open the file
fclose(file);
fopen("$filename", "r");
int ctr = 0; // Indexing for the array.
while(fgets(buffer, 50, file)) {
char* word = malloc(sizeof(char) * (strlen(buffer) + 1));
strcpy(myArray[ctr], word);
ctr++;
free(word);
}
for (int i = 0; i < count; i++) {
printf("%s\n", myArray[ctr]); // This just prints 7 new lines.
}