iomenu

interactive text selection menu
Log | Files | Refs | README | LICENSE

commit 376d9cfc1451c3e416065b0fdd958c491b9b4a93
parent 223058fdf9e2427b8ec9ec01df7185c074b545a7
Author: Josuah Demangeon <mail@josuah.net>
Date:   Sun, 15 Oct 2017 23:26:30 +0200

split line reading function

Diffstat:
Miomenu.c | 41++++++++++++++++++++++++++---------------
1 file changed, 26 insertions(+), 15 deletions(-)

diff --git a/iomenu.c b/iomenu.c @@ -53,13 +53,31 @@ die(const char *s) exit(EXIT_FAILURE); } +static char * +read_line(FILE *fp) +{ + char *line; + size_t len; + + line = malloc(LINE_MAX + 1); + if (!(fgets(line, LINE_MAX, fp))) { + free(line); + return NULL; + } + + len = strlen(line); + if (len > 0 && line[len - 1] == '\n') + line[len - 1] = '\0'; + + return (line); +} + static void -read_lines(void) +read_stdin(void) { int size = 0; - size_t len; - do { + while (1) { if (linec >= size) { size += BUFSIZ; linev = realloc(linev, sizeof (char **) * size); @@ -67,18 +85,11 @@ read_lines(void) if (!linev || !matchv) die("realloc"); } - - linev[linec] = malloc(LINE_MAX + 1); - if (!(fgets(linev[linec], LINE_MAX, stdin))) { - free(linev[linec]); + if ((linev[linec] = read_line(stdin)) == NULL) break; - } - - len = strlen(linev[linec]); - if (len > 0 && linec[linev][len - 1] == '\n') - linev[linec][len - 1] = '\0'; - - } while (++linec, ++matchc); + linec++; + matchc++; + } } static void @@ -537,7 +548,7 @@ main(int argc, char *argv[]) parse_opt(argc, argv); - read_lines(); + read_stdin(); filter(); if (!freopen("/dev/tty", "r", stdin)) die("freopen /dev/tty");