diff options
| author | Julian Weigt <juw@posteo.de> | 2026-01-16 10:54:58 +0100 |
|---|---|---|
| committer | Julian Weigt <juw@posteo.de> | 2026-02-04 15:55:53 +0100 |
| commit | 5c0dc646b78e2d7ef25088ac78397e2ed613cba1 (patch) | |
| tree | 645be2ddd7979157c29cf4aeb98ba4342e69dea7 /misc.c | |
| parent | 96916ac21687177bdf519d51919feeda5376b09f (diff) | |
Move getLine to mics.c.
Diffstat (limited to 'misc.c')
| -rw-r--r-- | misc.c | 31 |
1 files changed, 31 insertions, 0 deletions
@@ -0,0 +1,31 @@ +//for reading from stdin +#include <string.h> + +#define OK 0 +#define NO_INPUT 1 +#define TOO_LONG 2 + +static int getLine (char *prmpt, char *buff, size_t sz) { + int ch, extra; + + // Get line with buffer overrun protection. + if (prmpt != NULL) { + printf ("%s", prmpt); + fflush (stdout); + } + 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') { + 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; +} |
