I am having trouble sorting a dirent struct in C. I have tried everything and cannot get the values of my struct array to appear in my comparison. My code looks like this:
void printSortedNames(){
struct dirent **file_list = (dirent**)malloc(5 * sizeof(dirent*));
int i = 0;
for (i = 0; i < directory_size; ++i){
file_list[i] = (dirent*)malloc(50 * sizeof(dirent));
}
DIR *dir;
struct dirent *sd;
dir = opendir(".");
if (dir == NULL){
printf("Error! unable to open directory.\n");
exit(1);
}
int count = 0;
while ((sd = readdir(dir)) != NULL){
file_list[count] = sd;
printf("%s\n", file_list[count]->d_name);
++count;
}
size_t file_list_size = sizeof(&file_list) / sizeof(struct dirent);
qsort(file_list, file_list_size, sizeof(struct dirent), sizeCompare);
}
I have created a simple function sizeCompare to show that my function is working but I get null values. My function looks like:
int sizeCompare(const void* a, const void* b){
printf("%s\n", ((const struct dirent*)a)->d_name);
}
Can someone explain to me why my sizeCompare is not retrieve the array values correctly?
UPDATE: I have tried playing around with the size in the qsort and my value as a result was no longer null. the following line gives me an output:
qsort(file_list, 1000, sizeof(struct dirent), sizeCompare);
Obviously 1000 is not a good solution. Does anybody know the correct size for an array like this?
UPDATE 2: sizeCompare function only takes the first parameter and the second one is null.
int sizeCompare(const void* a, const void* b){
const struct dirent *first_dirent = *(const struct dirent **) a;
const struct dirent *second_dirent = *(const struct dirent **) b;
.......
//first one works but second one is NULL
}