From 8c07c676867594da5c2307226117ba9550630173 Mon Sep 17 00:00:00 2001 From: Jakob Kaivo Date: Tue, 6 Aug 2019 14:17:42 -0400 Subject: do lines from the end --- tail.c | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/tail.c b/tail.c index 742fed8..92e0e01 100644 --- a/tail.c +++ b/tail.c @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -59,18 +60,36 @@ static int tail(const char *path, int follow, int unit, intmax_t count) } while (count < 0) { - count = (-count) + 1; + count = -count; if (unit == BYTES) { + count++; char buf[count]; intmax_t pos = 0; while ((c = getc(f)) != EOF) { buf[pos++] = c; - if (pos >= count) { + if (pos == count) { pos = 0; } } fwrite(buf + pos, 1, count - pos, stdout); fwrite(buf, 1, pos, stdout); + break; + } + + intmax_t line = 0; + char buf[count][LINE_MAX]; + while (fgets(buf[line], sizeof(buf[line]), f) != NULL) { + line++; + if (line == count) { + line = 0; + } + } + + for (intmax_t i = line; i < count; i++) { + fputs(buf[i], stdout); + } + for (intmax_t i = 0; i < line; i++) { + fputs(buf[i], stdout); } } -- cgit v1.2.1