1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
int trier(const char* file)
{
FILE *p_fichier = fopen(file,"r");
if (p_fichier == NULL) {
return 0;
}
int choix;
printf("Veuillez choisir le critére: \n");
printf("1. Tri croissant par nom.\n");
printf("2. Tri décroissant par nom.\n");
printf("3. Tri croissant par prénom.\n");
printf("4. Tri décroissant par prénom.\n");
printf("5. Tri croissant par taille.\n");
printf("6. Tri décroissant par taille.\n");
printf("faites votre choix: ");
scanf("%d", &choix);
// on compte tout les éléments du fichier
// en meme temps,on met chaque fiche dans un tableau dynamique
int nb_fiches=1;
t_element *tab_fiches;
tab_fiches = malloc(sizeof(t_element));
if (tab_fiches == NULL) {
printf("Allocation Impossible.\n");
return 0;
}
tab_fiches[nb_fiches-1] = lire_element(p_fichier);
while (!feof(p_fichier))
{
nb_fiches++;
// on agrandit le tableau pour chaque nouvelle fiche
// on utilise une variable temporaire pour éviter la fuite de mémoire
t_element * temp;
temp = realloc (tab_fiches, nb_fiches * sizeof(t_element) );
if ( temp == NULL ) {
printf("Reallocation impossible.\n");
free(tab_fiches);
return 0;
}
else
tab_fiches = temp;
tab_fiches[nb_fiches-1] = lire_element(p_fichier);
}
// on tri le tableau
// création d'un fichier temporaire
FILE *ftemp;
if((ftemp = fopen("temp.tmp", "w")) == NULL) {
fclose(p_fichier);
return 0;
}
// écriture des fiches trié dans le fichier temporaire
int i;
for (i=0;i<nb_fiches-1;i++)
fprintf("%s %s %d\n", tab_fiches[i].nom,tab_fiches[i].prenom,tab_fiches[i].taille);
// mise à jour du fichier
free(tab_fiches);
fclose(p_fichier);
fclose(ftemp);
remove(file);
rename("temp.tmp",file);
remove("temp.tmp");
return 1;
} |
Partager