summaryrefslogtreecommitdiff
path: root/functions.c
diff options
context:
space:
mode:
authorLuke Bratch <luke@bratch.co.uk>2019-04-18 01:58:02 +0200
committerLuke Bratch <luke@bratch.co.uk>2019-04-18 01:58:02 +0200
commit84b3f43a97da2b305cfa5c620aceec543168f6bc (patch)
treef6cda57d836c6e606648e135d300016510c8e115 /functions.c
parent7d5fbb2c855ebe7e2a0dc373bfd3943e4728c750 (diff)
Split functions into different files
Diffstat (limited to 'functions.c')
-rw-r--r--functions.c52
1 files changed, 52 insertions, 0 deletions
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';
+}