Fixed file read bug #17

This commit is contained in:
2017-05-21 17:09:18 +02:00
parent bdca40555d
commit f2333e87ef

View File

@@ -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';