On Oct 11 21:27:54, j...@wxcvbn.org wrote: > Jan Stary <h...@stare.cz> writes: > > > The diff below makes head(1) recognize `-' > > as a name for the standard input, > > as many other utilities do. > > Makes sense to me. The following points could be improved IMO:
Updated diff below. > - using strcmp sounds cleaner than those char comparisons OK > - I don't think the man page bits are needed. Utilities that read from > stdin are supposed to support `-'. I'm not sure whether the extra > example is really helpful. I have removed the example. I think the one sentence about "-" should stay; other utils which recognize "-" mention it. > - should we avoid closing stdin (multiple times)? fixed OK? Jan Index: head.1 =================================================================== RCS file: /cvs/src/usr.bin/head/head.1,v retrieving revision 1.23 diff -u -p -r1.23 head.1 --- head.1 25 Oct 2015 21:50:32 -0000 1.23 +++ head.1 11 Oct 2016 21:05:07 -0000 @@ -47,6 +47,9 @@ utility copies the first lines of each specified .Ar file to the standard output. +A name of +.Sq - +is recognized as standard input. If no files are named, .Nm copies lines from the standard input. Index: head.c =================================================================== RCS file: /cvs/src/usr.bin/head/head.c,v retrieving revision 1.21 diff -u -p -r1.21 head.c --- head.c 20 Mar 2016 17:14:51 -0000 1.21 +++ head.c 11 Oct 2016 21:05:07 -0000 @@ -30,6 +30,7 @@ */ #include <stdio.h> +#include <string.h> #include <stdlib.h> #include <ctype.h> #include <limits.h> @@ -93,7 +94,8 @@ main(int argc, char *argv[]) if (pledge("stdio", NULL) == -1) err(1, "pledge"); } else { - if ((fp = fopen(*argv, "r")) == NULL) { + fp = strcmp(*argv, "-") ? fopen(*argv, "r") : stdin; + if (fp == NULL) { warn("%s", *argv++); status = 1; continue; @@ -101,7 +103,8 @@ main(int argc, char *argv[]) if (argc > 1) { if (!firsttime) putchar('\n'); - printf("==> %s <==\n", *argv); + printf("==> %s <==\n", + fp == stdin ? "(stdin)" : *argv); } ++argv; } @@ -109,7 +112,8 @@ main(int argc, char *argv[]) while ((ch = getc(fp)) != EOF) if (putchar(ch) == '\n') break; - fclose(fp); + if (fp != stdin) + fclose(fp); } /*NOTREACHED*/ }