c - 如何从文件中获取随机结构?
问题描述
我有一个包含许多结构的文件,每个结构都包含一个问题、它的答案和一个标识号。所以我创建了一个返回文件中结构数量的函数,以及另一个生成 1 和结构数量之间的随机数的函数。这两个函数单独工作正常,但是当我尝试在下面的函数中使用生成的随机数时,程序在 while 的第一个循环中停止......另一方面,当我为 randNum 定义一个值时,函数做它应该做的事情:它检查每个结构的 id,如果 id 等于 randNum 定义的值,问题就会打印在屏幕上。
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.
//This one counts the number of structs in the file
int structCounter(FILE *arq){
int count;
int sz;
fseek(arq, 0L, SEEK_END);
sz = ftell(arq);
count= sz/sizeof(question);
return count;
}
//This one generates a random number, using the return of the previous function as a limit
int generateRandom(int count){
int random;
srand(time(NULL));
random= 1+rand()%count;
return random;
}
解决方案
我刚刚发现出了什么问题。我没有在函数 structCounter() 中的 seek() 之后添加命令 rewind()。现在它似乎工作得很好。谢谢大家的帮助!
推荐阅读
- javascript - Telegraf 从 Telegram API 发送图像
- git - 当我们在vscode中点击“accept both changes”时,合并冲突时会执行哪个命令?
- visual-studio - 如何在 Visual Studio 中调试启动之前强制评估 startarguments
- java - 如何在Spring中为每个类使用抽象实体和条件属性类型WITH表
- reactjs - 创建动态组件而不是复制 Reactjs
- javascript - 角度展开/折叠表格行 - 使用 ng-bootstrap
- docker - 超集 - OAuth - “没有名为 authlib 的模块”
- django - 如何将预定义的表单列表和条件字典添加到 Sessionwizard (Django 2.2)?
- android - FlatList 在 React Native 中不滚动
- flutter - 如何更正此颤动错误:位置 0 处 JSON 中的意外标记 a?