diff options
author | Tavian Barnes <tavianator@tavianator.com> | 2021-05-08 11:57:06 -0400 |
---|---|---|
committer | Tavian Barnes <tavianator@tavianator.com> | 2021-09-15 12:31:33 -0400 |
commit | b2d85ea84c930ebcfefc6449414ed64cd80e2f89 (patch) | |
tree | 889ffeb0c2cdd67791a7ceefd2cc8b915b18a1d7 /util.c | |
parent | ea1aa067aeaf41db8e463eb95d64ebdac6002851 (diff) | |
download | bfs-b2d85ea84c930ebcfefc6449414ed64cd80e2f89.tar.xz |
util: Wrap getdelim() instead of open coding it
Diffstat (limited to 'util.c')
-rw-r--r-- | util.c | 47 |
1 files changed, 20 insertions, 27 deletions
@@ -266,31 +266,6 @@ bool is_nonexistence_error(int error) { return error == ENOENT || errno == ENOTDIR; } -/** Read a line from standard input. */ -static char *xgetline(void) { - char *line = dstralloc(0); - if (!line) { - return NULL; - } - - while (true) { - int c = fgetc(stdin); - if (c == '\n' || c == EOF) { - break; - } - - if (dstrapp(&line, c) != 0) { - goto error; - } - } - - return line; - -error: - dstrfree(line); - return NULL; -} - /** Compile and execute a regular expression for xrpmatch(). */ static int xrpregex(nl_item item, const char *response) { const char *pattern = nl_langinfo(item); @@ -339,9 +314,9 @@ static int xrpmatch(const char *response) { int ynprompt() { fflush(stderr); - char *line = xgetline(); + char *line = xgetdelim(stdin, '\n'); int ret = line ? xrpmatch(line) : -1; - dstrfree(line); + free(line); return ret; } @@ -433,3 +408,21 @@ char *xconfstr(int name) { return str; } + +char *xgetdelim(FILE *file, char delim) { + char *chunk = NULL; + size_t n = 0; + ssize_t len = getdelim(&chunk, &n, delim, file); + if (len >= 0) { + if (chunk[len] == delim) { + chunk[len] = '\0'; + } + return chunk; + } else { + free(chunk); + if (!ferror(file)) { + errno = 0; + } + return NULL; + } +} |