该代码最终将用于对.ct成员对包含文件信息的结构数组进行排序。 (st_ctime)。到目前为止,qsort似乎还不知道每个struct的开始位置。它没有排序。 (我知道scandir具有alphasort。)
将比较函数更改为strcmp()即可。
typedef struct filerec {
char *nm; int sz; int ct; // name, size, ctime
} frec_t;
int cmp(const void *s1, const void *s2) {
// compare ctimes
if(((frec_t *)s1)->ct > ((frec_t *)s2)->ct) return 1;
if(((frec_t *)s1)->ct < ((frec_t *)s2)->ct) return -1;
return 0;
}
void tst(frec_t ***ra_ptr) { // build & populate array
int i, qt = 3; // real quantity will come from scandir
srand(time(NULL));
for(i = 0; i < qt; i++) {
*ra_ptr = realloc(*ra_ptr, (i + 1) * sizeof(frec_t *));
(*ra_ptr)[i] = malloc(sizeof(frec_t));
(*ra_ptr)[i]->nm = malloc(6);
// in real life copy a file name returned by scandir
sprintf((*ra_ptr)[i]->nm, "file%d", i + 1);
// in real life assign the ctime return by stat
(*ra_ptr)[i]->ct = rand();
}
for(i = 0; i < qt; i++)
printf("%s %12d\n", (*ra_ptr)[i]->nm, (*ra_ptr)[i]->ct);
qsort(*ra_ptr, qt, sizeof(frec_t *), cmp);
// output is always the same despite rand/qsort
for(i = 0; i < qt; i++)
puts((*ra_ptr)[i]->nm);
// and the same problem occurs with real data
}
void main(void) {
frec_t **rec_a = NULL;
tst(&rec_a);
}