Random line selector added

This commit is contained in:
trollhase 2013-11-02 18:36:24 +01:00
parent 631c14889e
commit 122e673838
1 changed files with 51 additions and 0 deletions

51
random.c Normal file
View File

@ -0,0 +1,51 @@
#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;
}