From 84b3f43a97da2b305cfa5c620aceec543168f6bc Mon Sep 17 00:00:00 2001 From: Luke Bratch Date: Thu, 18 Apr 2019 01:58:02 +0200 Subject: Split functions into different files --- functions.c | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 functions.c (limited to 'functions.c') diff --git a/functions.c b/functions.c new file mode 100644 index 0000000..73302b8 --- /dev/null +++ b/functions.c @@ -0,0 +1,52 @@ +#include "functions.h" + +// Print a debugging message, if debugging enabled +int debugmode; +void debug(char *string) { + if (debugmode) { + printf("DEBUG: %s\n", string); + } +} + +// Get stdin line with buffer overrun protection +int getstdin(char *prompt, char *buff, size_t sz) { + int ch, extra; + + // Print optional prompt + if (prompt != NULL) { + printf ("%s", prompt); + fflush (stdout); + } + + // Get the intput from stdin + if (fgets (buff, sz, stdin) == NULL) { + return NO_INPUT; + } + + // If it was too long, there'll be no newline. In that case, we flush + // to end of line so that excess doesn't affect the next call. + if (buff[strlen(buff) - 1] != '\n') { // strlen of the actually entered line, not the original array size + extra = 0; + while (((ch = getchar()) != '\n') && (ch != EOF)) { + extra = 1; + } + return (extra == 1) ? TOO_LONG : OK; + } + + // Otherwise remove newline and give string back to caller. + buff[strlen(buff) - 1] = '\0'; + return OK; +} + +// Append CR-LF to the end of a string (after cleaning up any existing trailing CR or LF) +void appendcrlf(char *string) { + // Make sure it doesn't already end with CR or LF + while (string[strlen(string) - 1] == '\r' || string[strlen(string) - 1] == '\r') { + string[strlen(string) - 1] = '\0'; + } + + int startlen = strlen(string); + string[startlen] = '\r'; + string[startlen + 1] = '\n'; + string[startlen + 2] = '\0'; +} -- cgit v1.2.3