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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define STR_MAX 100
void* malloc(size_t nombreOctetsNecessaires);
struct string
{
char str[STR_MAX] ;
int len ;
} ;
struct string * lit_fichier(char *nom_fichier, int *nb)
{
FILE *f ;
int i = 0 ;
int j = 0 ;
char *chaine = NULL ;
struct string *tab = NULL ;
f = fopen(nom_fichier,"r") ;
printf("avant comptage %d %d \n", i, *nb) ;
/* On compte le nombre de mots */
fgets(chaine, 20, f) ;
printf("%s ",chaine) ;
while ( (i<*nb) && ( fgets(chaine, 20, f) ) != NULL) {
printf("pendant comptage %d \n", i) ;
i++ ;
}
*nb = i ;
printf("apres comptage %d \n", *nb) ;
/* Retour au début du fichier */
fseek(f, 0, SEEK_SET) ;
/* Allocation dynamique et vérification */
tab = malloc(*nb * sizeof(char*)) ;
if (tab == NULL ){
fprintf(stderr,"Allocation impossible \n");
exit(EXIT_FAILURE);
}
printf("avant lecture dans lecture %d \n", *nb) ;
/* Lecture du fichier */
while ( (j < *nb) && ( fgets(chaine, 20, f) != NULL ) ){
strcpy(tab[j].str, chaine) ;
tab[j].len = strlen(tab[j].str - 1) ;
j++ ;
}
printf("apres lecture dans lecture %d \n", j) ;
fclose(f) ;
return tab ;
}
void affichage(struct string tab[], int longueur)
{
int i ;
for ( i = 0 ; i < longueur ; i++ ) {
printf("%s (%d) \n" , tab[i].str, tab[i].len) ;
}
}
int main(int argc, char *argv[])
{
FILE *f ;
struct string *tableau ;
int nb = 10 ;
/* Ouverture du fichier */
if ( argc == 1 ) {
fprintf(stderr, "Il me faudrait un nom de fichier ...\n") ;
return 1 ;
}
f = fopen(argv[1], "r") ;
if ( f == NULL ) {
fprintf(stderr, "Impossible de lire le fichier [%s].\n", argv[1]) ;
return 2 ;
}
fclose(f) ;
printf("avant lecture %d \n", 1);
tableau = lit_fichier(argv[1], &nb) ;
printf("après lecture %d \n", 2);
affichage(tableau, nb) ;
printf("après affichage %d \n",3) ;
/* Libération de la mémoire */
free(tableau) ;
tableau = NULL ;
} |
Partager