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
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define ERR_CANT_OPEN 1
#define ERR_CANT_ALLOC 2
int main()
{
FILE* lire ;
int i,j,nbMots ;
char c ;
char** mots=NULL ; /* Ce tableau dynamique contiendra la liste de mots */
char* l = "./ToBeSorted" ;
/* Ouverture du fichier a trier */
lire = fopen(l,"r") ; ;
if(lire==NULL)
exit(ERR_CANT_OPEN) ;
/* Parcours de lignes du fichier */
/* i indique la ligne courante, j le caractère courant */
for(i=0 ; !(feof(lire)) ; i++)
{
j=0 ;
/* Allocation d'une nouvelle chaine dynamique dans le tableau */
mots=realloc(mots,(i+1)*sizeof(char*)) ;
if(mots==NULL){
exit(ERR_CANT_ALLOC) ;
}
/*mots[i]=NULL ;*/ /* Decommenter cette ligne pour que le programme marche */
/* Lecture des caractere de la ligne */
c=fgetc(lire) ;
while(((c!='\r') && (c!='\n')) && (!feof(lire)))
{
printf("+++ %d,%d:%c +++\n",i,j,c);
/* Allocation d'un caratère supplémentaire */
mots[i]=realloc(mots[i],(j+1)*sizeof(char)) ; /* <- SEGFAULT */
if(mots[i]==NULL){
exit(ERR_CANT_ALLOC) ;
}
printf("---\n") ;
/* Ecriture du caratère */
mots[i][j]=c ;
j++ ;
c=fgetc(lire) ;
}
/* Ajout du '\0' */
mots[i]=realloc(mots[i],(j+1)*sizeof(char)) ;
if(mots[i]==NULL){
exit(ERR_CANT_ALLOC) ;
}
mots[i][j]='\0' ;
}
nbMots=i ;
fclose(lire) ;
/* traitement de la liste de mots... */
return 0 ;
} |
Partager