diff --git a/usr.bin/head/head.c b/usr.bin/head/head.c index 5de0cba..cee5ae2 100644 --- a/usr.bin/head/head.c +++ b/usr.bin/head/head.c @@ -61,8 +61,8 @@ __FBSDID("$FreeBSD$"); * Bill Joy UCB August 24, 1977 */ -static void head(FILE *, int); -static void head_bytes(FILE *, off_t); +static void head(FILE *, int, int); +static void head_bytes(FILE *, off_t, int); static void obsolete(char *[]); static void usage(void); @@ -71,18 +71,21 @@ main(int argc, char *argv[]) { int ch; FILE *fp; - int first, linecnt = -1, eval = 0; + int first, linecnt = -1, eval = 0, pipekp = 0; off_t bytecnt = -1; char *ep; obsolete(argv); - while ((ch = getopt(argc, argv, "n:c:")) != -1) + while ((ch = getopt(argc, argv, "c:kn:")) != -1) switch(ch) { case 'c': bytecnt = strtoimax(optarg, &ep, 10); if (*ep || bytecnt <= 0) errx(1, "illegal byte count -- %s", optarg); break; + case 'k': + pipekp = 1; + break; case 'n': linecnt = strtol(optarg, &ep, 10); if (*ep || linecnt <= 0) @@ -112,21 +115,21 @@ main(int argc, char *argv[]) first = 0; } if (bytecnt == -1) - head(fp, linecnt); + head(fp, linecnt, pipekp); else - head_bytes(fp, bytecnt); + head_bytes(fp, bytecnt, pipekp); (void)fclose(fp); } } else if (bytecnt == -1) - head(stdin, linecnt); + head(stdin, linecnt, pipekp); else - head_bytes(stdin, bytecnt); + head_bytes(stdin, bytecnt, pipekp); exit(eval); } static void -head(FILE *fp, int cnt) +head(FILE *fp, int cnt, int keep) { char *cp; size_t error, readlen; @@ -137,10 +140,12 @@ head(FILE *fp, int cnt) err(1, "stdout"); cnt--; } + for (; keep && fgetln(fp, &readlen) != NULL;) + ; /* nothing */ } static void -head_bytes(FILE *fp, off_t cnt) +head_bytes(FILE *fp, off_t cnt, int keep) { char buf[4096]; size_t readlen; @@ -157,6 +162,8 @@ head_bytes(FILE *fp, off_t cnt) err(1, "stdout"); cnt -= readlen; } + for (; keep && fread(buf, sizeof(char), readlen, fp);) + ; /* nothing */ } static void @@ -181,6 +188,6 @@ static void usage(void) { - (void)fprintf(stderr, "usage: head [-n lines | -c bytes] [file ...]\n"); + (void)fprintf(stderr, "usage: head [-k] [-c bytes | -n lines] [file ...]\n"); exit(1); }