You read each line of data into the same buffer, so the last line overwrites all previous lines. You're going to have to allocate space for each line by some means or other - either dynamic memory allocation with malloc()
(or possibly strdup()
), or using a fixed size array (which limits the amount of data your program can handle safely). You'll also need to deal with newlines in the data read.
You get some credit for using fgets()
and not using gets()
; that is a 100% correct decision.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
enum { MAXLINES = 30 };
int main(void)
{
int i = 0;
char lines[MAXLINES][BUFSIZ];
FILE *fp = fopen("input.txt", "r");
if (fp == 0)
{
fprintf(stderr, "failed to open input.txt
");
exit(1);
}
while (i < MAXLINES && fgets(lines[i], sizeof(lines[0]), fp))
{
lines[i][strlen(lines[i])-1] = '';
i = i + 1;
}
fclose(fp);
printf("%d
", i);
srand(time(0));
int j = rand() % i;
int k = (j+1) % i;
printf("%s %s
", lines[j], lines[k]);
return 0;
}
This checks that the file was opened successfully, closes the file as soon as the reading is complete, and ensures that it does not trigger a stack overflow by reading more lines than the array can hold. It wastes a lot of space by over-allocating space so each line could be very long (though the lines are typically quite short). If a line is longer than BUFSIZ, it will be read into a couple of adjacent entries in lines
. It does not assume that there are 8 lines in the data file. It zaps the newline at the end of each line (unless a line is split, in which case it zaps the last character before the split on the first of the two lines). It seeds the random number generator with the current time. It seems odd that you only ever want adjacent lines from the file.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…