how can i order a date struct in c?


i have this program, where i have a struct, where i have to save, from a file.txt, some dates (day-month-year). after that, i have to make some controls on it, like visualize, visualize on a certain order, ecc... im trying to visualize the struct in ascent order, so from the "lowest" date to the "highest". im using the qsort function, but when i use it, it just order the days, and not the months and the years.

how can i solve this problem? i leave the code down here.

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

struct date{            //<-- struct for the dates
    int giorno;
    int mese;
    int anno;
};

struct date *leggi_file(FILE *fp, int *size){       //<-- im reading the file and saving the text in the struct
    int dim = 16;
    struct date *d;
    if(!(d = malloc(dim *sizeof(struct date)))){
        free(d);
        return NULL;
    }
    char buf[60];
    while(fgets(buf, sizeof(buf), fp) != NULL){
        if(3 != sscanf(buf, "%d/%d/%d", &d[*size].giorno, &d[*size].mese, &d[*size].anno)){
            puts("data incompleta");
            continue;
        }
    (*size) = (*size) +1;
        if(dim >= (*size)){
            dim *= 2;
            if(!(d = realloc (d, dim * sizeof(struct date))))
                return 0;
        }
    }
    d = realloc(d,(*size) * sizeof(struct date));
    return d;
}

void stampafile(struct date *d, int size){      //<-- im printing on screen the file
    int i;

    for(i=0; i<size; i++){
        printf("%d giorno %d mese %d anno\n", d[i].giorno, d[i].mese, d[i].anno);
    }
}

int cmpfunc(const void *a, const void *b){
    return (*(int*)a - *(int*)b);
}

void ordinadate(struct date *d, int size){
    int i;
    qsort(d, size, sizeof(*d), cmpfunc);
    printf("\nqsort giorni\n");

    for(i=0; i<size; i++){
        printf("%d %d %d\n", d[i].giorno, d[i].mese, d[i].anno);
    }
}

int main(int argc, char *argv[]){
    struct date *d;
    FILE *fp;
    fp = fopen(argv[1],"r");
    int size= 0;

    if(fp == 0){
        return 1;
    }
    
    if(!(d = leggi_file(fp, &size))){
        return 0;
    }

    stampafile(d, size);
    ordinadate(d, size);        //function orderdate
    fclose(fp);
    free(d);
}

the txt file is like:

10/12/2012
10/11/2011
07/06/2001
...

---------------Answer---------------

Doing this:

int cmpfunc(const void *a, const void *b){
    return (*(int*)a - *(int*)b);
}

you are comparing only the first member of the struct: giorno.

You need to compare all members:

int cmpfunc(const void *a, const void *b){
    const struct date *pa = a;
    const struct date *pb = b;

    int anno = pa->anno - pb->anno;
    int mese = pa->mese - pb->mese;
    int giorno = pa->giorno - pb->giorno;

    return anno != 0 ? anno :
           mese != 0 ? mese :
           giorno;
}

Previous : Python: How to add Firefox extensions in Selenium 4
Next : How to target an element that has been rendered in a for loop - VUE