one-file-projects/random.c

51 lines
840 B
C
Raw Normal View History

2013-11-02 18:36:24 +01:00
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#define MAX_LINES 200
#define LINEBUF 1024
int main() {
char* lines[MAX_LINES];
int n = 0;
char buf[LINEBUF];
char* line;
int len;
//Read first line
line = fgets(buf, LINEBUF, stdin);
while(line != NULL && n < MAX_LINES) {
//Get len of line
len = strlen(line);
//Create space for line
char* linecpy = malloc(len+1);
//Copy line
strcpy(linecpy,line);
//Add line to array.
lines[n++] = linecpy;
//Read next line
line = fgets(buf, LINEBUF, stdin);
}
if(n > 0) {
//Prepare random seed
srand(time(NULL)*getpid());
//Generate random number
int r = rand() % n;
//Print random line
fputs(lines[r],stdout);
//Free all lines.
int i;
for(i = 0; i < n; i++) {
free(lines[i]);
}
}
return 0;
}