Files
TD3_DEV51_vaisse_kara-mosr/getfuncs.c

80 lines
1.3 KiB
C
Raw Normal View History

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