From 8d7ff35875187031e3cb1253dc6a7a54407597bf Mon Sep 17 00:00:00 2001 From: Arthur-Coppey Date: Sun, 22 Aug 2021 01:03:21 +0200 Subject: [PATCH] random quote done --- server/quote.c | 52 +++++++++++++++++++++++++++++++++++++++++--------- server/quote.h | 10 ++++++++-- 2 files changed, 51 insertions(+), 11 deletions(-) diff --git a/server/quote.c b/server/quote.c index bcc0f38..5c746b4 100644 --- a/server/quote.c +++ b/server/quote.c @@ -4,20 +4,54 @@ #include "quote.h" -void getRandomQuote(char quote[1024]) { - // TODO: true random between 0 and number of lines in file - int rand = 0; - getQuote(rand, quote); +void getRandomQuote(char quote[2048]) { + int lineCount; + long line; + + if ((lineCount = getFileLineCount(QUOTES_FILE)) == -1) { + puts("file does not exist"); + exit(-1); + } + + line = random() % lineCount; + + getQuote(line, quote); } -void getQuote(int line, char quote[1024]) { +void getQuote(long line, char quote[2048]) { FILE* list; - // TODO: get specified x line + list = fopen(QUOTES_FILE, "r"); - list = fopen("quotes.txt", "r"); - - fgets(quote, 1024, list); + /*skip lines*/ + while (line > 0) { + if (fgetc(list) == '\n') { + line--; + } + } + fgets(quote, 2048, list); + quote[strlen(quote) - 1] = '\0'; fclose(list); } + +int getFileLineCount(char *filename) { + char c; + int lineCount = 0; + FILE* quotesFile = fopen(filename, "r"); + + if (quotesFile == NULL) { + printf("no quote file found at \"%s\"\n", filename); + return -1; + } + + while ((c = (char) fgetc(quotesFile)) != EOF) { + if (c == '\n') { + lineCount++; + } + } + + fclose(quotesFile); + + return lineCount; +} diff --git a/server/quote.h b/server/quote.h index a18b61e..fba8603 100644 --- a/server/quote.h +++ b/server/quote.h @@ -6,11 +6,17 @@ #define QOTD_QUOTE_H #include +#include +#include #include #include -void getRandomQuote(char quote[1024]); +#define QUOTES_FILE "./quotes.txt" -void getQuote(int line, char quote[1024]); +void getRandomQuote(char quote[2048]); + +void getQuote(long line, char quote[2048]); + +int getFileLineCount(char* filename); #endif //QOTD_QUOTE_H