mardi 18 mai 2021

How to get a random struct from a file?

I have a file with a number of structs that contains a question, its answer and an identification number as well, each. So I created a function that returns the number of structs in the file, and another function that generates a random number between 1 and the number of structs. Individually these two functions work fine, but when I try to use the generated random number in the function below, it just does not work... what should I do? (if I change the value of randNum to a defined number, the function works perfectly.)

void generalKnowledge(){
header();
FILE* arquivo;
question qst;
int num=0;
int temp;

arquivo= fopen("generalKnowledge.txt", "rb");
if(arquivo==NULL){
    printf("Falha ao abrir arquivo!\n");//"Failed to open file!"
}
else{

    int randNum;
    randNum= generateRandom(structCounter(arquivo));

    while(fread(&qst, sizeof(question), 1, arquivo)==1){
        
        if(randNum==qst.id){
            num++;
            printf(ANSI_COLOR_YELLOW "Questao %d: %s\n\n" ANSI_COLOR_RESET, num, qst.question);
            printf(ANSI_COLOR_MAGENTA "a) %s\n" ANSI_COLOR_RESET, qst.opta);
            printf(ANSI_COLOR_MAGENTA "b) %s\n" ANSI_COLOR_RESET, qst.optb);
            printf(ANSI_COLOR_MAGENTA "c) %s\n" ANSI_COLOR_RESET, qst.optc);
            printf(ANSI_COLOR_MAGENTA "d) %s\n" ANSI_COLOR_RESET, qst.optd);
            printf("\n\n");
        }
    }
    
}
fclose(arquivo);

}

//Below, the two first functions that I mentioned.

int structCounter(FILE *arq){
int count;
int sz;

fseek(arq, 0L, SEEK_END);
sz = ftell(arq);

count= sz/sizeof(question);

return count;

}

int generateRandom(int count){
int random;
srand(time(NULL));
random= 1+rand()%count;
return random;

}




Aucun commentaire:

Enregistrer un commentaire