From a05ee6629c8dba5fac315fd73ba94c101c1124ff Mon Sep 17 00:00:00 2001 From: nothing-c <55337124+nothing-c@users.noreply.github.com> Date: Tue, 4 Oct 2022 17:20:14 -0500 Subject: Add tab width specification (#5) Add default value for tabsize, fix usage of width where it should have tabsize, fix optarg string, limit tabsize to being non-negative only. --- center.c | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/center.c b/center.c index 57b5473..9099584 100644 --- a/center.c +++ b/center.c @@ -52,6 +52,7 @@ extern char *optarg; int rval; long width; +long tabwidth = 8; int (*lenfunc)(const char *) = noesclen; int @@ -61,7 +62,7 @@ main(int argc, char **argv) char *endptr; void (*centerfunc)(FILE *) = center; - while ((opt = getopt(argc, argv, ":elw:")) != -1) { + while ((opt = getopt(argc, argv, ":elsw:t:")) != -1) { switch (opt) { case 'e': lenfunc = utf8len; @@ -75,11 +76,20 @@ main(int argc, char **argv) if (errno == ERANGE || width > INT_MAX) warnx("Potential overflow of given width"); break; + case 't': + tabwidth = strtol(optarg, &endptr, 0); + if (*optarg == '\0' || *endptr != '\0') + errx(EXIT_FAILURE, "Invalid integer '%s'", optarg); + if (tabwidth < 0) + errx(EXIT_FAILURE, "Tab width must be >=0"); + if (errno == ERANGE || tabwidth > INT_MAX) + warnx("Potential overflow of given tab size"); + break; case 'l': centerfunc = center_by_longest; break; default: - fprintf(stderr, "Usage: %s [-e] [-w width] [file ...]\n", argv[0]); + fprintf(stderr, "Usage: %s [-e] [-w width] [-t tab width] [file ...]\n", argv[0]); exit(EXIT_FAILURE); } } @@ -126,7 +136,7 @@ center(FILE *fp) tabs++; } - len = lenfunc(line) + tabs * 8 - tabs; + len = lenfunc(line) + tabs * tabwidth - tabs; for (int i = (width - len) / 2; i >= 0; i--) putchar(' '); fputs(line, stdout); -- cgit v1.2.3