From 94f1c52e676e0590eba761946002ad50f3346e5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?John=20Ankarstr=C3=B6m?= Date: Sat, 7 Nov 2020 00:16:30 +0100 Subject: add stdin support --- l.c | 61 +++++++++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 41 insertions(+), 20 deletions(-) diff --git a/l.c b/l.c index 53a1dbe..bbc5081 100644 --- a/l.c +++ b/l.c @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -15,16 +16,13 @@ #define prn(...) dprintf(ttyfd, __VA_ARGS__) #define rerr(...) do { raw(false); err(__VA_ARGS__); } while (0) -char *lines[3] = { - "line 1", - "line 2", - "line 3" -}; +char **lines; +int lines_c; +int lines_s; int current = -1; /* currently selected item */ -int height = 3; /* height of output in rows */ -int ttyfd; int x, y; /* original cursor position in cols, rows */ +int ttyfd; /* enable/disable "raw" mode */ void raw(bool enable) { @@ -88,7 +86,7 @@ int cpr(int *x, int *y) { /* select item */ int item(int n) { - if (n < 1 || n > height) return -1; + if (n < 1 || n > lines_c) return -1; if (current != -1) prn("%s", lines[current - 1]); current = n; @@ -106,15 +104,45 @@ int right() {} int left() {} int main() { - char c, *p, *phrase; - int i, r; + char c, *line, *p, *phrase, *tmp; + int i, line_s, r; struct winsize w; - phrase = NULL; ttyfd = open("/dev/tty", O_RDWR); if (ttyfd == -1) rerr(1, "open"); + /* read from standard input */ + + line_s = 100; + line = malloc((line_s + 1) * sizeof(char)); + if (line == NULL) err(1, "malloc"); + + lines_c = 0; + lines_s = 50; + lines = malloc(lines_s * sizeof(char *)); + if (lines == NULL) err(1, "malloc"); + + i = 0; + while (read(STDIN_FILENO, &c, 1) != 0) { + if (c == '\n') { + line[i] = '\0'; + lines[lines_c] = malloc((strlen(line) + 1) * sizeof(char)); + if (lines[lines_c] == NULL) err(1, "malloc"); + strcpy(lines[lines_c], line); + lines_c++; + i = 0; + } else { + if (i > line_s) { + line_s += 50; + tmp = realloc(line, (line_s + 1) * sizeof(char)); + if (tmp == NULL) err(1, "realloc"); + line = tmp; + } + line[i++] = c; + } + } + raw(true); /* save original cursor position */ @@ -125,22 +153,15 @@ int main() { } /* print output */ - for (i = 0; i < height; i++) + for (i = 0; i < lines_c; i++) prn("%s\r\n", lines[i]); - /* get height of output */ - /* - p = ex - 1; - height = 0; - while (*(++p) != '\0') - if (*p == '\n') height++; - /* get height of terminal */ r = ioctl(ttyfd, TIOCGWINSZ, &w); if (r == -1) rerr(1, "ioctl"); /* correct cursor position if original cursor was near bottom */ - r = y + height - w.ws_row; + r = y + lines_c - w.ws_row; if (r > 0) y = y - r; -- cgit v1.2.3