From 9dc2da1f901c68ed5d631e1890e0e9e9e730d54f Mon Sep 17 00:00:00 2001 From: Nakidai Date: Sun, 29 Oct 2023 21:31:33 +0300 Subject: [PATCH] Add input function --- Makefile | 2 +- include/input.h | 14 ++++++++++++++ src/input.c | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 include/input.h create mode 100644 src/input.c diff --git a/Makefile b/Makefile index 65dc3a9..2163dbc 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ LD = ld RM = rm -f SRCDIR = src OBJDIR = obj -SRC = main.c screen.c +SRC = main.c screen.c input.c OBJ = $(addprefix $(OBJDIR)/,$(SRC:.c=.o)) default: $(OUT) diff --git a/include/input.h b/include/input.h new file mode 100644 index 0000000..2b65a7a --- /dev/null +++ b/include/input.h @@ -0,0 +1,14 @@ +#ifndef __INPUT_H__ +#define __INPUT_H__ + +#include + +typedef struct input_args_t +{ + char *out; + bool *alive; +} inputArgs; + +void input(void *vargp); + +#endif /* __INPUT_H__ */ diff --git a/src/input.c b/src/input.c new file mode 100644 index 0000000..8d4f8a7 --- /dev/null +++ b/src/input.c @@ -0,0 +1,33 @@ +#include "input.h" +#include +#include +#include + +char getch(void) +{ + char buf = 0; + struct termios old = { 0 }; + fflush(stdout); + if (tcgetattr(0, &old) < 0) perror("tcsetattr()"); + old.c_lflag &= ~ICANON; // local modes = Non Canonical mode + old.c_lflag &= ~ECHO; // local modes = Disable echo. + old.c_cc[VMIN] = 1; // control chars (MIN value) = 1 + old.c_cc[VTIME] = 0; // control chars (TIME value) = 0 (No time) + if (tcsetattr(0, TCSANOW, &old) < 0) perror("tcsetattr ICANON"); + if (read(0, &buf, 1) < 0) perror("read()"); + old.c_lflag |= ICANON; // local modes = Canonical mode + old.c_lflag |= ECHO; // local modes = Enable echo. + if (tcsetattr(0, TCSADRAIN, &old) < 0) perror ("tcsetattr ~ICANON"); + return buf; +} + +void input(void *vargp) +{ + char *out = ((inputArgs *)vargp)->out; + bool *alive = ((inputArgs *)vargp)->alive; + + while (*alive) + { + *out = getch(); + } +}