diff --git a/hangman.c b/hangman.c index a15b4e6..03b0362 100644 --- a/hangman.c +++ b/hangman.c @@ -369,19 +369,16 @@ int centerDiff(int coordinate, char *str) { } void readRandomLine(char *file, char *result) { - long totalLength = 0, rand = 0; FILE *fp = fopen(file, "r"); - char c; - int wordlength = 0; - - while ((c = fgetc(fp)) != EOF) { - if (c == '\n') ++totalLength; + int count = 0, wordlength = 0; + char line[MAXWORDLENGTH]; + srand(time(NULL)); + while (fgets(line, MAXWORDLENGTH, fp) != NULL) { + count++; + if ((rand() / (float)RAND_MAX) <= (1.0 / count)) { + strcpy(result, line); + } } - - rand = getrandom(0, totalLength); - fseek(fp, -rand, SEEK_END); - - fgets(result, MAXWORDLENGTH, fp); /* remove \n at the end of the line */ wordlength = strlen(result); result[wordlength - 1] = '\0';