diff --git a/TODO b/TODO index 5ee4076..0d7d367 100644 --- a/TODO +++ b/TODO @@ -52,3 +52,4 @@ FIX: xargs (-d) echo (escape) que (unicode) + ps (-o) diff --git a/src/head.c b/src/head.c index 8ac62b8..a6a982c 100644 --- a/src/head.c +++ b/src/head.c @@ -1,5 +1,12 @@ #define _HEAD_C +#ifdef _TAIL_C +#define PROG_NAME "tail" +#else +#define PROG_NAME "head" +#define _TAIL_C 0 +#endif + #include #include #include @@ -16,10 +23,13 @@ static long parse_long(const char *str) { char *ptr; long ret = strtol(str, &ptr, 0); if (*ptr) { - fprintf(stderr, "head: invalid number %s\n", ptr); + fprintf(stderr, "%s: invalid number %s\n", PROG_NAME, ptr); exit(1); } + if (_TAIL_C && ret < 0) + ret *= -1; + return ret; } @@ -31,7 +41,7 @@ static int print(const char *file, FILE *fp, long lines, long bytes) { long bcount = 0; /* If lines or bytes < 0 */ - if (lines < 0 || bytes < 0) { + if ((lines < 0 || bytes < 0) || _TAIL_C) { long lmax = 0; long bmax = 0; @@ -39,10 +49,11 @@ static int print(const char *file, FILE *fp, long lines, long bytes) { size_t buf_size = 0; char *buf = malloc(1); if (buf == NULL) { - fprintf(stderr, "head: malloc: %s\n", strerror(errno)); + fprintf(stderr, "%s: malloc: %s\n", PROG_NAME, strerror(errno)); return 1; } + /* Fill buffer */ while (1) { int c = getc(fp); if (c == EOF) @@ -50,7 +61,7 @@ static int print(const char *file, FILE *fp, long lines, long bytes) { char *tmp = realloc(buf, buf_size + 2); if (tmp == NULL) { - fprintf(stderr, "head: realloc: %s\n", strerror(errno)); + fprintf(stderr, "%s: realloc: %s\n", PROG_NAME, strerror(errno)); free(buf); return 1; @@ -72,9 +83,15 @@ static int print(const char *file, FILE *fp, long lines, long bytes) { lcount++; bcount++; - putchar(buf[i]); - if ((n_flag && lcount == lmax + lines) || (c_flag && bcount == bmax + bytes)) - break; + + if ((c_flag && bmax - bcount < bytes) || (n_flag && lmax - lcount < lines)) + putchar(buf[i]); + + else if (!_TAIL_C) { + putchar(buf[i]); + if ((n_flag && lcount == lmax + lines) || (c_flag && bcount == bmax + bytes)) + break; + } } free(buf); @@ -121,7 +138,7 @@ int main(int argc, char **argv) { break; default: - puts("head [ncv] [file1 file2...]\n\t-n Print [-]N lines\n\t-c Print [-]N bytes\n\t-v Print headers"); + printf("%s [ncv] [file1 file2...]\n\t-n Print [-]N lines\n\t-c Print [-]N bytes\n\t-v Print headers\n", PROG_NAME); return 0; } } @@ -142,7 +159,7 @@ int main(int argc, char **argv) { fp = fopen(argv[i], "r"); if (fp == NULL) { - fprintf(stderr, "head: %s: %s\n", argv[i], strerror(errno)); + fprintf(stderr, "%s: %s: %s\n", PROG_NAME, argv[i], strerror(errno)); ret = 1; continue; diff --git a/src/tail.c b/src/tail.c new file mode 100644 index 0000000..7d0d04e --- /dev/null +++ b/src/tail.c @@ -0,0 +1,2 @@ +#define _TAIL_C 1 +#include "head.c"