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
| #include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#include "test.h"
#define MAX_CHAR 100
void n_alea(int maxi, int *n)
{
*n = rand() % maxi + 1;
}
int calculer(FILE *file)
{
int counter = 0;
char *line = malloc(MAX_CHAR * sizeof(char));
while(fgets(line, MAX_CHAR, file)) ++counter;
free(line);
return counter;
}
void chercher(char *mot, FILE *file, int n_line)
{
int counter = 0;
if (file == NULL)
{
puts("Erreur de lecture");
exit(1);
}
while (counter != n_line)
{
fgets(mot, MAX_CHAR, file);
if(mot == NULL)
{
puts("Ligne non trouvée");
exit(1);
}
counter++;
}
}
int main(void)
{
int aleatoire, MAX;
char fichier[] = "/home/fred1599/Desktop/test.txt";
char word[MAX_CHAR];
FILE *fic;
srand ( time(NULL) );
fic = fopen(fichier, "r");
MAX = calculer(fic); /* Nombre de lignes du fichier de mots */
n_alea(MAX, &aleatoire); /* Générer un nombre aléatoire entre 1 et le nombre de lignes du fichier */
chercher(word, fic, aleatoire); /* Cherche un mot dans le fichier */
printf("%s\n", word); /* Affichage du mot */
return 0;
} |
Partager