summaryrefslogtreecommitdiff
path: root/tail.c
diff options
context:
space:
mode:
authorJakob Kaivo <jkk@ung.org>2019-08-06 14:17:42 -0400
committerJakob Kaivo <jkk@ung.org>2019-08-06 14:17:42 -0400
commit8c07c676867594da5c2307226117ba9550630173 (patch)
treed307eac2efb698ebaf568fd09c3123c98ca5d4e1 /tail.c
parent03600a8c07b89dcad1c3ec21d1d2c01673e278e3 (diff)
do lines from the end
Diffstat (limited to 'tail.c')
-rw-r--r--tail.c23
1 files 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 <ctype.h>
#include <errno.h>
#include <inttypes.h>
+#include <limits.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
@@ -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);
}
}