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) {
|
void readRandomLine(char *file, char *result) {
|
||||||
long totalLength = 0, rand = 0;
|
|
||||||
FILE *fp = fopen(file, "r");
|
FILE *fp = fopen(file, "r");
|
||||||
char c;
|
int count = 0, wordlength = 0;
|
||||||
int wordlength = 0;
|
char line[MAXWORDLENGTH];
|
||||||
|
srand(time(NULL));
|
||||||
while ((c = fgetc(fp)) != EOF) {
|
while (fgets(line, MAXWORDLENGTH, fp) != NULL) {
|
||||||
if (c == '\n') ++totalLength;
|
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 */
|
/* remove \n at the end of the line */
|
||||||
wordlength = strlen(result);
|
wordlength = strlen(result);
|
||||||
result[wordlength - 1] = '\0';
|
result[wordlength - 1] = '\0';
|
||||||
|
Reference in New Issue
Block a user