From d5a9b8d6502ab787791ad75c0494436ed2326c23 Mon Sep 17 00:00:00 2001 From: Jan-Piet Mens Date: Sat, 29 Aug 2015 15:40:36 +0200 Subject: [PATCH] Implement forward reader (cat) as for the reverse reader (tac) --- util.c | 34 ++++++++++++++++++++++++++++++++++ util.h | 1 + 2 files changed, 35 insertions(+) diff --git a/util.c b/util.c index a28f87c..6c122e4 100644 --- a/util.c +++ b/util.c @@ -261,6 +261,40 @@ static char *tac_gets(char *buf, int n, FILE * fp) return (buf); } +/* + * Open filename and read lines from it, invoking func() on each line. Func + * is passed the line and an arbitrary argument pointer. + * If filename is "-", read stdin. + */ + +int cat(char *filename, int (*func)(char *, void *), void *param) +{ + FILE *fp; + char buf[LINESIZE], *bp; + int rc = 0, doclose = FALSE; + + if (strcmp(filename, "-") != 0) { + if ((fp = fopen(filename, "r")) == NULL) { + fprintf(stderr, "failed to open file \'%s\'\n", filename); + return (-1); + } + doclose = TRUE; + } else { + fp = stdin; + } + + while (fgets(buf, sizeof(buf), fp) != NULL) { + if ((bp = strchr(buf, '\n')) != NULL) + *bp = 0; + rc = func(buf, param); + if (rc == -1) + break; + } + if (doclose) + fclose(fp); + return (rc); +} + /* * Open file and read at most `lines' lines from it in reverse, invoking * func() on each line. The user-supplied func() is passed the line and diff --git a/util.h b/util.h index 4620cca..41c7d53 100644 --- a/util.h +++ b/util.h @@ -18,5 +18,6 @@ JsonNode *json_splitter(char *s, char *sep); int syslog_facility_code(char *facility); const char *yyyymm(time_t t); int tac(char *filename, long lines, int (*func)(char *, void *), void *param); +int cat(char *filename, int (*func)(char *, void *), void *param); #endif