The hard part is working out how to get a random line from the file when you don't know how many lines there are. One way is to read the file once and count the lines, then use that count to pick a random number. A cooler way is a survivor method. Read lines and use a random test to pick between two lines. The one you picked is the survivor. When you get to the end of the file, the survivor will be randomly picked from all of the lines:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
char *getLine(FILE *fp, char line[], size_t limit);
void getRandomLine(const char *filename, char line[], size_t limit);
int main()
{
char line[1024];
int i;
srand((unsigned)time(NULL));
/* Get 10 random lines from the file */
for (i = 0; i < 10; ++i) {
getRandomLine("test.txt", line, sizeof line);
printf("%s\n", line);
}
}
char *getLine(FILE *fp, char line[], size_t limit)
{
char *result = fgets(line, limit, fp);
if (result != NULL) {
/* Strip the newline character */
char *nl = strchr(line, '\n');
if (nl != NULL)
*nl = '\0';
}
return result;
}
void getRandomLine(const char *filename, char line[], size_t limit)
{
FILE *fp = fopen(filename, "r");
if (fp != NULL) {
/* Get the first line as the first survivor */
if (getLine(fp, line, limit) != NULL) {
char *temp = (char*)malloc(limit);
/* Survivor method starting with the first 2 lines */
while (getLine(fp, temp, limit) != NULL) {
if (rand() % 2 == 0)
strcpy(line, temp);
}
/* Clean up resources */
free(temp);
fclose(fp);
}
}
} It gets kind of inefficient if you ask for a lot of random lines though. The best solution is to keep the whole file in memory and just use random indexes if it's small enough. :)