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) { 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';