Implement forward reader (cat) as for the reverse reader (tac)

This commit is contained in:
Jan-Piet Mens
2015-08-29 15:40:36 +02:00
parent b8252b4bd5
commit d5a9b8d650
2 changed files with 35 additions and 0 deletions
+34
View File
@@ -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
+1
View File
@@ -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