Files
TD3_DEV51_vaisse_kara-mosr/getfuncs.c
vaisse 87487bde84 mince
2025-10-08 17:25:49 +02:00

80 lines
1.3 KiB
C

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
/*
récupère le nombre de lignes dans la banque de mots
*/
int getFileLength(){
/*variables*/
FILE* stream;
int file_length = 0;
char* line = NULL;
size_t length = 0;
ssize_t read;
/*prog*/
stream = fopen("wordbank.txt", "r");
if (stream == NULL){
return EXIT_FAILURE;
}
while((read = getline(&line, &length, stream)) != -1){
file_length++;
}
fclose(stream);
return file_length-1;
}
/*
récupère un mot aléatoire dans la banque de mots
*/
int fetchWord(char* fullword, int file_length){
/*variables*/
FILE* stream;
int random = (rand() * time(NULL)) % (file_length);
char read[8];
unsigned int counter = 0;
int char_size = (int) sizeof(char);
int line=0;
int offset=0;
/*prog*/
printf("%d\n", random);
stream = fopen("wordbank.txt", "r");
if (stream == NULL){
return -1;
}
while((!feof(stream))&&(offset!=random)){
fread(read, sizeof(char), 1, stream);
if(*read=='\n'){
offset++;
}
}
*read=' ';
while(*read!='\n'){
fread(read, sizeof(char), 1, stream);
fullword[counter] = *read;
counter++;
}
fclose(stream);
return 0;
}
int main(void){
int flength;
char fullWord[128];
flength = getFileLength();
if(fetchWord(fullWord, flength)!=-1){
printf("%s", fullWord);
}
return EXIT_SUCCESS;
}