forked from yos-r/hangman
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdico.c
421 lines (376 loc) · 12.5 KB
/
dico.c
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "dico.h"
#include <unistd.h>
int piocherMot(char *motPioche)
{
FILE *dico = NULL; // Le pointeur de fichier qui va contenir notre fichier
int nombreMots = 0, numMotChoisi = 0, i = 0;
int caractereLu = 0;
dico = fopen("dictionnaire.txt", "r"); // On ouvre le dictionnaire en lecture seule
// On vérifie si on a réussi à ouvrir le dictionnaire
if (dico == NULL) // Si on n'a PAS réussi à ouvrir le fichier
{
printf("\nImpossible de charger le dictionnaire de mots");
return 0; // On retourne 0 pour indiquer que la fonction a échoué
// À la lecture du return, la fonction s'arrête immédiatement.
}
// On compte le nombre de mots dans le fichier (il suffit de compter les
// entrées \n
do
{
caractereLu = fgetc(dico);
if (caractereLu == '\n')
nombreMots++;
} while (caractereLu != EOF);
numMotChoisi = nombreAleatoire(0, nombreMots); // On pioche un mot au hasard // On recommence à lire le fichier depuis le début. On s'arrête lorsqu'on est arrivé au bon mot
printf("\n le num choisi est %d: \n", numMotChoisi);
rewind(dico);
while (numMotChoisi > 0)
{
caractereLu = fgetc(dico);
if (caractereLu == '\n')
numMotChoisi--;
}
/* Le curseur du fichier est positionné au bon endroit.
On n'a plus qu'à faire un fgets qui lira la ligne */
fgets(motPioche, 100, dico);
printf("\n le mot pioche est %s: \n", motPioche);
// On vire le \n à la fin
motPioche[strlen(motPioche) - 1] = '\0';
printf("\n le mot pioche est apres trans %s: \n", motPioche);
fclose(dico);
return 1; // Tout s'est bien passé, on retourne 1
}
int nombreAleatoire(int nombreMin, int nombreMax)
{
srand(time(NULL));
return (rand() % (nombreMax - nombreMin + 1)) + nombreMin;
}
int compareStrings(const void *a, const void *b)
{
return strcmp(*(const char **)a, *(const char **)b);
}
void sortDictionary()
{
FILE *file = fopen("dictionnaire.txt", "r");
if (file == NULL)
{
printf("Error opening the file for reading.\n");
// Handle the error appropriately
return;
}
char **words = NULL;
char word[1000];
int wordCount = 0;
while (fgets(word, 1000, file) != NULL)
{
word[strcspn(word, "\n")] = '\0';
char *newWord = strdup(word);
words = (char **)realloc(words, (wordCount + 1) * sizeof(char *));
if (words == NULL)
{
printf("Memory allocation error.\n");
fclose(file);
return;
}
words[wordCount] = newWord;
wordCount++;
}
fclose(file);
// Sort the array
qsort(words, wordCount, sizeof(char *), compareStrings);
file = fopen("dictionnaire.txt", "w");
if (file == NULL)
{
printf("Error opening the file for writing.\n");
return;
}
for (int i = 0; i < wordCount; i++)
{
fprintf(file, "%s\n", words[i]);
// Free memory allocated for each word
free(words[i]);
}
free(words);
fclose(file);
}
void addToDictionary(const char *word)
{
FILE *file = fopen("dictionnaire.txt", "a");
if (file != NULL)
{
fprintf(file, "%s\n", word);
fclose(file);
}
else
{
printf("Error opening the file for writing.\n");
}
sortDictionary();
}
void dicoInsererMot(char mot[], ArbreBin **arbre, QueueNode **queue)
{
if (*arbre != NULL)
/*si l'arbre n'est pas vide*/
{
if (mot[0] != '\0')
/*on teste si la premiemre valeur egale au premier char de mot*/
{
if ((*arbre)->val == mot[0])
{
/*si egale Incrémente la position du pointeur dans la chaîne de caractères mot. */
mot++;
/*et fait l'appelle recursive du fonction sur la fils gauche*/
dicoInsererMot(mot, &((*arbre)->FG), queue);
}
else
{
/*si l'arbre a un fils droite on cherche le char*/
if ((*arbre)->FD != NULL)
{
/*on fait l'appel recursive de la fonction sur la fils droite*/
dicoInsererMot(mot, &((*arbre)->FD), queue);
}
else
{ /*si l'arbre vide on fait l'app au fonction arbreConNoeud pour on instialise l'arbre*/
(*arbre)->FD = arbreConNoeud(mot[0], NULL, NULL);
dicoInsererMot(mot, &(*arbre), queue); /*et on fait l app recursive au fonction pour isererer d'autre char */
}
}
}
/*si le mot n'est pas inserer dans l'arbre on fait l'appel au fonction arbreConNoeud pour insialiser une mot dans une arbre*/
else if ((*arbre)->val != '\0' && mot[0] == '\0')
{
ArbreBin *a = arbreConNoeud('\0', NULL, *arbre);
*arbre = a;
}
}
else
{
if (mot[0] != '\0' && mot[0] != '\r')
/*si toute le mot n'est pas inserer */
{ /*on fait l'appel recursiv sur la fils gauche pour inserer les autres char*/
*arbre = arbreConNoeud(mot[0], NULL, NULL);
mot++;
dicoInsererMot(mot, &((*arbre)->FG), queue);
}
/*sinon on insere /0 donc on a inserer tout les chars*/
else
{
*arbre = arbreConNoeud('\0', NULL, NULL);
}
}
}
void creerDictionnaire(ArbreBin **dictionnaire, char ***motArray, int *motCount)
{
FILE *dico = fopen("dictionnaire.txt", "r");
if (dico == NULL)
{
printf("\nImpossible de charger le dictionnaire de mots");
return;
}
char mot[100];
*motCount = 0;
while (fgets(mot, sizeof(mot), dico) != NULL)
{
(*motCount)++;
}
*motArray = (char **)malloc(*motCount * sizeof(char *));
if (*motArray == NULL)
{
printf("\nMemory allocation error");
fclose(dico);
return;
}
rewind(dico);
for (int i = 0; i < *motCount; i++)
{
(*motArray)[i] = (char *)malloc(100 * sizeof(char));
if ((*motArray)[i] == NULL)
{
printf("\nMemory allocation error");
fclose(dico);
for (int j = 0; j < i; j++)
{
free((*motArray)[j]);
}
free(*motArray);
return;
}
fgets((*motArray)[i], 100, dico);
(*motArray)[i][strcspn((*motArray)[i], "\n")] = '\0';
dicoInsererMot((*motArray)[i], dictionnaire, NULL);
}
fclose(dico);
sortDictionary();
}
int rechercherMot(const char *file_path, const char *search_word)
{
FILE *file = fopen(file_path, "r");
if (file == NULL)
{
printf("Erreur : fichier '%s' non trouvé.\n", file_path);
return 0;
}
int occurrence = 0;
char buffer[100];
while (fscanf(file, "%s", buffer) == 1)
{
if (strcmp(buffer, search_word) == 0)
{
occurrence++;
}
}
fclose(file);
return occurrence;
}
void visualiserCaracteristiquesDictionnaire()
{
FILE *file = fopen("dictionnaire.txt", "r");
if (file == NULL)
{
printf("Error: File '%s' not found.\n", "dictionnaire.txt");
return;
}
int total_words = 0;
int total_characters = 0;
int shortest_length = -1;
int longest_length = -1;
int word_count_by_length[20] = {0}; // Assuming words have lengths between 1 and 20 characters
char buffer[100];
while (fscanf(file, "%s", buffer) == 1)
{
int length = strlen(buffer);
total_words++;
total_characters += length;
if (shortest_length == -1 || length < shortest_length)
{
shortest_length = length;
}
if (length > longest_length)
{
longest_length = length;
}
if (length >= 1 && length <= 20)
{
word_count_by_length[length - 1]++;
}
}
fclose(file);
double average_length = total_characters / (double)total_words;
printf("\nStatistiques du dictionnaire :\n");
printf("==============================\n");
printf("Nombre total de mots : \x1b[32m%d\x1b[0m\n", total_words);
printf("Longueur moyenne des mots : \x1b[34m%.2f\x1b[0m caractères\n", average_length);
printf("Longueur du mot le plus court : \x1b[31m%d\x1b[0m caractères\n", shortest_length);
printf("Longueur du mot le plus long : \x1b[33m%d\x1b[0m caractères\n", longest_length);
printf("\nNombre de mots par longueur :\n");
for (int i = 0; i < 20; i++)
{
if (word_count_by_length[i] != 0)
printf(" Longueur %d caractères : %d mots\n", i + 1, word_count_by_length[i]);
}
printf("==============================\n\n");
char user_choice;
printf("\nVoulez-vous rechercher un mot spécifique? (O/N): ");
scanf(" %c", &user_choice);
if (user_choice == 'O' || user_choice == 'o')
{
char search_word[100];
printf("Entrez le mot à rechercher : ");
scanf("%s", search_word);
int occurrence = rechercherMot("dictionnaire.txt", search_word);
if (occurrence > 0)
{
printf("Le mot '%s' existe dans le dictionnaire et apparaît %d fois.\n", search_word, occurrence);
}
else
{
char add_choice;
printf("Le mot '%s' n'existe pas dans le dictionnaire. Voulez-vous l'ajouter? (O/N): ", search_word);
scanf(" %c", &add_choice);
if (add_choice == 'O' || add_choice == 'o')
{
FILE *file = fopen("dictionnaire.txt", "a+");
if (file == NULL)
{
printf("Erreur lors de l'ouverture du fichier.\n");
}
fprintf(file, "%s\n", search_word);
fclose(file);
printf("Le mot '%s' a été ajouté au dictionnaire.\n", search_word);
// Display updated dictionary statistics
visualiserCaracteristiquesDictionnaire("dictionnaire.txt");
}
else
{
printf("Le mot '%s' n'a pas été ajouté au dictionnaire.\n", search_word);
}
}
}
}
void supprimerLignesVides(const char *nomFichier)
{
FILE *fichier = fopen(nomFichier, "r+");
if (fichier == NULL)
{
perror("Erreur lors de l'ouverture du fichier");
exit(EXIT_FAILURE);
}
const int tailleMaxMot = 100;
char mot[tailleMaxMot];
long positionLecture = 0;
long positionEcriture = 0;
while (fscanf(fichier, "%s", mot) == 1)
{
positionLecture = ftell(fichier);
fseek(fichier, positionEcriture, SEEK_SET);
fprintf(fichier, "%s\n", mot);
positionEcriture = ftell(fichier);
fseek(fichier, positionLecture, SEEK_SET);
}
ftruncate(fileno(fichier), positionEcriture);
fclose(fichier);
}
void supprimerMot(const char *nomFichier, const char *motASupprimer)
{
FILE *fichier = fopen(nomFichier, "r+");
if (fichier == NULL)
{
perror("Erreur lors de l'ouverture du fichier");
exit(EXIT_FAILURE);
}
const int tailleMaxMot = 100;
char mot[tailleMaxMot];
int occ = rechercherMot(nomFichier, motASupprimer);
if (occ == 0)
{
printf("\033[31m"); // Séquence d'échappement pour changer la couleur en rouge
printf(" ___ _ _ ___ ___ _ _ \n");
printf(" / _ \\| | | | _ \\/ __| | | | | \n");
printf(" | (_) | |_| | _/\\__ \\ |_| |_| \n");
printf(" \\___/ \\___/|_| |___/ (_) (_) \n");
printf("\033[0m"); // Séquence d'échappement pour réinitialiser la couleur à la couleur par défaut
printf("\n");
printf("\033[31m"); // Séquence d'échappement pour changer la couleur en rouge
printf("Desole, le mot \"%s\" n'existe pas dans le dictionnaire!\n", motASupprimer);
printf("\033[0m"); // Séquence d'échappement pour réinitialiser la couleur à la couleur par défaut
}
else
{
while (fscanf(fichier, "%s", mot) == 1)
{
if (strcmp(mot, motASupprimer) == 0)
{
fseek(fichier, -strlen(mot), SEEK_CUR);
fprintf(fichier, "%*s", (int)strlen(mot), ""); // Effacer le mot
fseek(fichier, 0, SEEK_CUR); // Déplacer le curseur à la position actuelle
}
}
}
fclose(fichier);
supprimerLignesVides("dictionnaire.txt");
}