#include "tp12.h" int chargeFmatieres(char *nomFich, Mat **tmat, int tmax) { int i = 0; Mat m; FILE *flot; printf("%d\n", i); flot = fopen(nomFich, "r"); if(flot == NULL) { printf("Pb d'ouverture du fichier %s.\n", nomFich); return -1; } m = lireMat(flot); while(!feof(flot)) { if(i == tmax) { printf("tbl plein !!!\n"); fclose(flot); return -2; } tmat[i] = (Mat *)malloc(sizeof(Mat)); if(tmat[i] == NULL) { printf("Pb du tableau !\n"); fclose(flot); return -3; } *tmat[i] = m; i = i +1; m = lireMat(flot); } fclose(flot); return i; } Mat lireMat(FILE *flot) { Mat m; fscanf(flot, "%s%d", m.code, &m.coef); fgets(m.design, 30, flot); m.design[strlen(m.design)-1] = '\0'; return m; } void afficheMat(Mat m) { printf("%s\t%d\t%s\n", m.code, m.coef, m.design); } void afficheTmat(Mat **tMat, int nbmat) { int i; for(i = 0; i < nbmat; i++) afficheMat(*tMat[i]); printf("\n"); } void libereEspaceA(Mat *tmat[], int nb) { int i; for(i = 0; i < nb; i++) free(tmat[i]); } void sauvTbin(Mat *tab[], int nb) { int i; FILE *flot; flot = fopen("matieres.bin", "wb"); if(flot == NULL) { printf("Pb d'ouverture du fichier matieres.bin"); return; } fprintf(flot, "%d\n", &nb); for(i = 0; i < nb; i++) fwrite(tab[i], sizeof(Mat), 1, flot); fclose(flot); } int rechdich(char *code, Mat **tmat, int nbmat, int *trouve) { int inf, sup, m; inf = 0; sup = nbmat -1; while(inf <= sup) { m = (inf + sup)/2; if(strcmp(code, tmat[m]->code) == 0) { *trouve = 1; return m; } if(strcmp(code, tmat[m]->code) < 0) sup = m - 1; else inf = m+ 1; } *trouve = 0; return inf; } int supprime(Mat **tMat, int nbmat) { char code[6], rep; int pas, trouve, i; printf("Donnez le code de la matière à supprimer :\n"); scanf("%s%*c", code); pas = rechdich(code, tMat, nbmat, &trouve); if(trouve == 0) printf("Aucune matière n'as été trouvé\n"); else{ afficheMat(*tMat[pas]); printf("Vouez vous vraiment supprimer ? :\n"); scanf("%c", &rep); if(rep == 'o') { free(tMat[pas]); for(i = pas; i < nbmat-1; i++) tMat[i] = tMat[i + 1]; nbmat = nbmat - 1; } } return nbmat; } void global(void) { Mat *tab[50]; int nb; char nomFich[20]; printf("Donnez le nom du fichier :\n"); scanf("%s", nomFich); nb = chargeFmatieres(nomFich, tab, 50); if(nb < 0) return; afficheTmat(tab, nb); nb = supprime(tab, nb); afficheTmat(tab, nb); nb = supprime(tab, nb); afficheTmat(tab, nb); sauvTbin(tab, nb); libereEspaceA(tab, nb); }