我正在尝试为一个小型文本行游戏创建一本字典。 我在假设文件中的行数未知的情况下编写了文件读取部分,因此我让它在执行开始时读取整个文件一次以计算行数。 最终目标是让它在文件中选择一个随机单词进行处理,并将其放入动态分配的指针中。
这是阅读部分的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
//declaration des fonctions :
void main(void){
//Declaration des variables :
unsigned char *motSecret=NULL; //mot à trouver
unsigned char *motAffich=NULL; //mot à afficher
unsigned char vide[]="****************************"; //chaine servant à initialisation affichage
unsigned char taille=0,saisie=0,essais=10,flag1=0,flag2=0,i=0,n=0; //variables et compteurs divers
int aleat=0;
FILE *dico=NULL; //variable qui lit le fichier
srand(time(NULL));
//initialisation du mot aleatoire :
dico=fopen("dico.txt","r"); //ouvre le fichier en lecture
if(dico==NULL) //gueule si ça n'a pas marché
{printf("###FATAL ERROR : FILE EXPECTED BUT RETURNED NULL###"); exit(0);}
else
{
while((n=fgetc(dico))!=EOF)
{
if(n=='\n') taille++; //compte le nombre de lignes
}
fclose(dico);
}
}
执行该命令时,程序会卡住,就像正在处理无限循环一样,并且处理器立即以 100% 使用,直到我使用 ctrl+c 强制它停止。
我正在 Linux 上使用 gcc (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609 编译并运行它。
如有任何建议,我们将不胜感激。
最佳答案
您已定义
unsigned char n;
如此循环
while((n=fgetc(dico))!=EOF)
永远不会终止,因为n
的值永远不会-1
。您有一个无限循环,它试图读取文件末尾之后的内容。
函数fgetc
返回一个int
值,所以你应该有
int n;
关于c - 用 C 程序读取文本文件导致处理器以 100% 运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58083428/