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
|
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#define DBG 1
static void purge(FILE *fp)
{
int c;
while ((c = fgetc(fp)) != '\n' && c != EOF)
{
}
}
static void clean (char *s, FILE *fp)
{
/* search ... */
char *p = strchr (s, '\n'); /* <string.h> */
if (p != NULL)
{
/* ... and kill */
*p = 0;
}
else
{
purge (fp);
}
}
int main (void)
{
char nomfichier[50];
printf("Indiquez l'emplacement et le nom du fichier a verifier (ex:C:\\..\\nom.txt)\n");
fgets(nomfichier, sizeof nomfichier, stdin);
clean(nomfichier, stdin);
{
FILE *fichier = fopen(nomfichier, "r");
if (fichier != NULL)
{
/* compter les mots */
int cpt = 0;
char tmp[50];
while ((fscanf(fichier, "%49s", tmp)) == 1)
{
#if DBG
printf ("%s\n", tmp);
#endif
cpt++;
}
printf("Il y a %d mots\n", cpt);
rewind(fichier);
{
char **pp_mots = malloc (cpt * sizeof * pp_mots);
if (pp_mots != NULL)
{
int i = 0;
while ((fscanf(fichier, "%49s", tmp)) == 1)
{
pp_mots[i] = strdup(tmp);
i++;
}
/* affichage */
for (i = 0; i < cpt; i++)
{
printf ("[%d] %s\n", i, pp_mots[i]);
}
/* liberation */
for (i = 0; i < cpt; i++)
{
free (pp_mots[i]), pp_mots[i] = NULL;
assert(pp_mots[i] == NULL);
}
free (pp_mots), pp_mots = NULL;
}
assert(pp_mots == NULL);
}
fclose (fichier), fichier = NULL;
}
else
{
perror (nomfichier);
}
assert(fichier == NULL);
}
return 0;
} |