From cf9fc1dfe5432e63554b7ba192938984ddf61c4a Mon Sep 17 00:00:00 2001 From: Li Zefan Date: Thu, 11 Oct 2007 13:57:35 +0200 Subject: [PATCH] tailf: add option -n to specifying output lines It will be useful if we can print out the last n lines instead of the last 10, just like tail. There are examples: tailf -n 5 file1 tailf --lines 10 file2 tailf -20 file3 Signed-off-by: Li Zefan Signed-off-by: Karel Zak --- text-utils/tailf.1 | 14 +++++++++----- text-utils/tailf.c | 32 +++++++++++++++++++++++++++----- 2 files changed, 36 insertions(+), 10 deletions(-) diff --git a/text-utils/tailf.1 b/text-utils/tailf.1 index ccce6628..8bc53fca 100644 --- a/text-utils/tailf.1 +++ b/text-utils/tailf.1 @@ -26,7 +26,8 @@ .SH NAME tailf \- follow the growth of a log file .SH SYNOPSIS -.BI tailf " file" +.B tailf +[\fIOPTION\fR] \fIfile\fR .SH DESCRIPTION .B tailf will print out the last 10 lines of a file and then wait for the file to @@ -40,10 +41,13 @@ does not occur periodically when no log activity is happening. is extremely useful for monitoring log files on a laptop when logging is infrequent and the user desires that the hard disk spin down to conserve battery life. -.SH BUGS -An option could be provided to print out the last -.I n -lines instead of the last 10. +.PP +Mandatory arguments to long options are mandatory for short options too. +.TP +\fB\-n\fR, \fB\-\-lines\fR=\fIN\fR, \fB\-N\fR +output the last +.I N +lines, instead of the last 10. .SH AUTHOR This program was written by Rik Faith (faith@acm.org) and may be freely distributed under the terms of the X11/MIT License. There is ABSOLUTELY diff --git a/text-utils/tailf.c b/text-utils/tailf.c index 5b1d1a4e..79a194da 100644 --- a/text-utils/tailf.c +++ b/text-utils/tailf.c @@ -33,8 +33,12 @@ #include #include #include +#include +#include "errs.h" #include "nls.h" +#define DEFAULT_LINES 10 + static size_t filesize(const char *filename) { struct stat sb; @@ -86,19 +90,37 @@ int main(int argc, char **argv) FILE *str; const char *filename; int count, wcount; + int lines = DEFAULT_LINES; setlocale(LC_ALL, ""); bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); - if (argc != 2) { - fprintf(stderr, _("Usage: tailf logfile\n")); - exit(1); + argc--; + argv++; + + for (; argc > 0 && argv[0][0] == '-'; argc--, argv++) { + if (!strcmp(*argv, "-n") || !strcmp(*argv, "--lines")) { + argc--; + argv++; + if (argc > 0 && (lines = atoi(argv[0])) <= 0) + errx(EXIT_FAILURE, _("Invalid number of lines")); + } + else if (isdigit(argv[0][1])) { + if ((lines = atoi(*argv + 1)) <= 0) + errx(EXIT_FAILURE, _("Invalid number of lines")); + } + else + errx(EXIT_FAILURE, _("Invalid option")); } - filename = argv[1]; + if (argc != 1) { + fprintf(stderr, _("Usage: tailf [-n N | -N] logfile\n")); + exit(EXIT_FAILURE); + } - tailf(filename, 10); + filename = argv[0]; + tailf(filename, lines); for (osize = filesize(filename);;) { nsize = filesize(filename); -- 2.39.5