aboutsummaryrefslogtreecommitdiff
path: root/toys/posix
diff options
context:
space:
mode:
authorElliott Hughes <enh@google.com>2019-07-22 16:24:46 -0700
committerRob Landley <rob@landley.net>2019-07-23 15:56:56 -0500
commitd818f5ad26b837aedd2e7ab32997508d5d1e846d (patch)
treefcd69d60d9e9f6fcc2278f75f773483ff832e517 /toys/posix
parentb30674681b9d72430a029ba7bd3e16a3139244f0 (diff)
downloadtoybox-d818f5ad26b837aedd2e7ab32997508d5d1e846d.tar.gz
nl: switch from getline() to loopfiles_lines().
This was basically just to help me think out loud while discussing loopfiles_lines().
Diffstat (limited to 'toys/posix')
-rw-r--r--toys/posix/nl.c46
1 files changed, 18 insertions, 28 deletions
diff --git a/toys/posix/nl.c b/toys/posix/nl.c
index 1b7b390a..ef2d7ab3 100644
--- a/toys/posix/nl.c
+++ b/toys/posix/nl.c
@@ -35,36 +35,25 @@ GLOBALS(
// Count of consecutive blank lines for -l has to persist between files
long lcount;
+ long slen;
)
-static void do_nl(int fd, char *name)
+static void do_nl(char **pline, long len)
{
- FILE *f = xfdopen(fd, "r");
- int w = TT.w, slen = strlen(TT.s);
-
- for (;;) {
- char *line = 0;
- size_t temp;
- int match = *TT.b != 'n';
-
- if (getline(&line, &temp, f) < 1) {
- if (ferror(f)) perror_msg_raw(name);
- break;
- }
-
- if (*TT.b == 'p') match = !regexec((void *)(toybuf+16), line, 0, 0, 0);
- if (TT.l || *TT.b == 't')
- if (*line == '\n') match = TT.l && ++TT.lcount >= TT.l;
- if (match) {
- TT.lcount = 0;
- printf(toybuf, w, TT.v++, TT.s);
- } else printf("%*c", (int)w+slen, ' ');
- xprintf("%s", line);
-
- free(line);
- }
-
- fclose(f);
+ char *line;
+ int match = *TT.b != 'n';
+
+ if (!pline) return;
+ line = *pline;
+
+ if (*TT.b == 'p') match = !regexec((void *)(toybuf+16), line, 0, 0, 0);
+ if (TT.l || *TT.b == 't')
+ if (*line == '\n') match = TT.l && ++TT.lcount >= TT.l;
+ if (match) {
+ TT.lcount = 0;
+ printf(toybuf, TT.w, TT.v++, TT.s);
+ } else printf("%*c", (int)(TT.w+TT.slen), ' ');
+ xprintf("%s", line);
}
void nl_main(void)
@@ -72,6 +61,7 @@ void nl_main(void)
char *clip = "";
if (!TT.s) TT.s = "\t";
+ TT.slen = strlen(TT.s);
if (!TT.n || !strcmp(TT.n, "rn")); // default
else if (!strcmp(TT.n, "ln")) clip = "-";
@@ -86,5 +76,5 @@ void nl_main(void)
REG_NOSUB | (toys.optflags&FLAG_E)*REG_EXTENDED);
else if (!strchr("atn", *TT.b)) error_exit("bad -b '%s'", TT.b);
- loopfiles (toys.optargs, do_nl);
+ loopfiles_lines(toys.optargs, do_nl);
}