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
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define TAILLE_MOT_MAX 128
char * choisirUnMot ( FILE * fichier , char * motAchercher , int nombreMots )
{
char mot[TAILLE_MOT_MAX];
int numero_ligne;
int ligne_courante;
numero_ligne = (int) ((double)rand() / (double)RAND_MAX * nombreMots) ;
ligne_courante = 0 ;
rewind(fichier);
while ( fgets(mot,TAILLE_MOT_MAX,fichier) != NULL )
{
if ( ligne_courante == numero_ligne )
{
char * position_caractere ;
position_caractere = strchr(mot,'\r');
if ( position_caractere != NULL )
*position_caractere = '\0' ;
position_caractere = strchr(mot,'\n');
if ( position_caractere != NULL )
*position_caractere = '\0' ;
strncpy(motAchercher,mot,TAILLE_MOT_MAX);
return motAchercher ;
}
ligne_courante++;
}
return NULL;
}
#define NOMBRE_MOTS 10 /* à adapter selon le nombre de mots dans le fichier texte */
int main( void )
{
char motAchercher[TAILLE_MOT_MAX] = "";
FILE * fichier ;
int i;
fichier = fopen ( "mots.txt" , "rb" );
if ( fichier == NULL )
return 0 ;
srand(time(NULL));
rand(); /* j'en mets un ici volontairement (la première valeur est toujours quasiment identique chez moi :o ) */
for ( i=0 ; i<50 ; i++) /* tire 50 mots au sort */
{
if ( choisirUnMot(fichier , motAchercher , NOMBRE_MOTS) != NULL )
{
printf("Mot : %s\n" , motAchercher);
} else
{
printf("Erreur\n");
}
}
fclose (fichier);
return 0;
} |
Partager