2011-05-27 06:13:38 -04:00
|
|
|
/* See LICENSE file for copyright and license details. */
|
2013-11-12 05:45:18 -05:00
|
|
|
#include <errno.h>
|
2011-05-26 13:18:42 -04:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <string.h>
|
|
|
|
#include <unistd.h>
|
|
|
|
#include "text.h"
|
|
|
|
#include "util.h"
|
|
|
|
|
|
|
|
static void dropinit(FILE *, const char *, long);
|
|
|
|
static void taketail(FILE *, const char *, long);
|
|
|
|
|
2013-06-14 14:20:47 -04:00
|
|
|
static void
|
|
|
|
usage(void)
|
|
|
|
{
|
|
|
|
eprintf("usage: %s [-n lines] [file]\n", argv0);
|
|
|
|
}
|
|
|
|
|
2011-05-26 13:18:42 -04:00
|
|
|
int
|
|
|
|
main(int argc, char *argv[])
|
|
|
|
{
|
|
|
|
long n = 10;
|
|
|
|
FILE *fp;
|
2011-05-26 13:29:22 -04:00
|
|
|
void (*tail)(FILE *, const char *, long) = taketail;
|
2013-08-31 16:53:11 -04:00
|
|
|
char *lines;
|
2011-05-26 13:18:42 -04:00
|
|
|
|
2013-06-14 14:20:47 -04:00
|
|
|
ARGBEGIN {
|
|
|
|
case 'n':
|
2013-08-31 16:53:11 -04:00
|
|
|
lines = EARGF(usage());
|
|
|
|
n = abs(estrtol(lines, 0));
|
|
|
|
if(lines[0] == '+')
|
2013-06-14 14:20:47 -04:00
|
|
|
tail = dropinit;
|
|
|
|
break;
|
2013-11-11 14:53:01 -05:00
|
|
|
ARGNUM:
|
|
|
|
n = ARGNUMF(0);
|
|
|
|
break;
|
2013-06-14 14:20:47 -04:00
|
|
|
default:
|
|
|
|
usage();
|
|
|
|
} ARGEND;
|
|
|
|
if(argc == 0) {
|
2011-05-26 13:18:42 -04:00
|
|
|
tail(stdin, "<stdin>", n);
|
2013-11-12 05:45:18 -05:00
|
|
|
} else {
|
|
|
|
for (; argc > 0; argc--, argv++) {
|
|
|
|
if(!(fp = fopen(argv[0], "r"))) {
|
|
|
|
fprintf(stderr, "fopen %s: %s\n", argv[0],
|
|
|
|
strerror(errno));
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
tail(fp, argv[0], n);
|
|
|
|
fclose(fp);
|
|
|
|
}
|
|
|
|
}
|
2011-05-26 13:18:42 -04:00
|
|
|
|
2013-10-07 11:41:55 -04:00
|
|
|
return EXIT_SUCCESS;
|
2011-05-26 13:18:42 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
void
|
|
|
|
dropinit(FILE *fp, const char *str, long n)
|
|
|
|
{
|
|
|
|
char buf[BUFSIZ];
|
|
|
|
long i = 0;
|
|
|
|
|
|
|
|
while(i < n && fgets(buf, sizeof buf, fp))
|
|
|
|
if(buf[strlen(buf)-1] == '\n')
|
|
|
|
i++;
|
|
|
|
concat(fp, str, stdout, "<stdout>");
|
|
|
|
}
|
|
|
|
|
|
|
|
void
|
|
|
|
taketail(FILE *fp, const char *str, long n)
|
|
|
|
{
|
|
|
|
char **ring;
|
|
|
|
long i, j;
|
2011-06-10 09:51:53 -04:00
|
|
|
size_t *size = NULL;
|
2011-05-26 13:18:42 -04:00
|
|
|
|
|
|
|
if(!(ring = calloc(n, sizeof *ring)) || !(size = calloc(n, sizeof *size)))
|
|
|
|
eprintf("calloc:");
|
|
|
|
for(i = j = 0; afgets(&ring[i], &size[i], fp); i = j = (i+1)%n)
|
|
|
|
;
|
2011-05-26 13:29:22 -04:00
|
|
|
if(ferror(fp))
|
|
|
|
eprintf("%s: read error:", str);
|
2011-05-26 13:18:42 -04:00
|
|
|
|
|
|
|
do {
|
2011-05-26 13:24:56 -04:00
|
|
|
if(ring[j]) {
|
2011-05-26 13:18:42 -04:00
|
|
|
fputs(ring[j], stdout);
|
2011-05-26 13:24:56 -04:00
|
|
|
free(ring[j]);
|
|
|
|
}
|
2011-05-26 13:18:42 -04:00
|
|
|
} while((j = (j+1)%n) != i);
|
|
|
|
free(ring);
|
|
|
|
free(size);
|
|
|
|
}
|