Fixed file read bug #17
This commit is contained in:
19
hangman.c
19
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';
|
||||
|
Reference in New Issue
Block a user