From 122e6738382f550d9c6f26e620f8e13106095ec7 Mon Sep 17 00:00:00 2001 From: trollhase Date: Sat, 2 Nov 2013 18:36:24 +0100 Subject: [PATCH] Random line selector added --- random.c | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 random.c diff --git a/random.c b/random.c new file mode 100644 index 0000000..efd8922 --- /dev/null +++ b/random.c @@ -0,0 +1,51 @@ +#include +#include +#include +#include +#include + +#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; +} \ No newline at end of file