From 7936ce26a0082b0795dac7933805e1f4d558a21c Mon Sep 17 00:00:00 2001 From: emma Date: Wed, 30 Aug 2023 19:01:07 -0600 Subject: [PATCH] tail(1p): trying from scratch --- src/tail.c | 58 ++++-------------------------------------------------- 1 file changed, 4 insertions(+), 54 deletions(-) diff --git a/src/tail.c b/src/tail.c index 61b9f89..4a74e2a 100644 --- a/src/tail.c +++ b/src/tail.c @@ -23,23 +23,11 @@ #include #include #include +#include #include #include "yac.h" -void tailc(FILE *file, long num) { - int byte; - char buf[num]; - long offset = -num; - - fseek(file, offset, SEEK_END); - for (int i = 0; (byte = fgetc(file)) != EOF; i++) { - buf[i] = byte; - } - - fputs(buf, stdout); -} - void tailf(FILE *file) { int byte; @@ -48,44 +36,6 @@ void tailf(FILE *file) { } } -void tailn(FILE *file, long num) { - char *buf = calloc(4096, 1); - char *lines[num]; - int byte; - int lc = 0; - - for (int bc = 0; (byte = fgetc(file)) != EOF; bc++) { - if (bc == sizeof(buf)) { - int err; - if (err = realloc(buf, sizeof(buf) * 2) == NULL) { - // TODO: error handling - } - } - - buf[bc] = byte; - - if (byte == '\n') { - lines[lc] = buf; - bc = 0; - lc++; - } - - if (lc == num) { - for (int i = 0; i < lc; i++) { - lines[i] = lines[i + 1]; - } - lc--; - } - } - - int i; - if ((i = lc - num) < 0) { i = 0; } - - for (; i < lc; i++) { - fputs(lines[i], stdout); - } -} - int main(int argc, char *argv[]) { bool c = false; bool f = false; @@ -140,13 +90,13 @@ int main(int argc, char *argv[]) { case 'c': c = true; fn = tailc; - num = (long)optarg; + num = strtol(optarg, NULL, 10); break; case 'f': f = true; case 'n': n = true; - num = (long)optarg; + num = strtol(optarg, NULL, 10); break; default: fprintf( @@ -179,10 +129,10 @@ int main(int argc, char *argv[]) { for (i = optind; i < argc; i++) { if ((file = rpath(argv[0], argv[i])) != NULL) { fn(file, num); - fclose(file); } if (f) { tailf(file); } + fclose(file); } } return EX_OK;