Re: head(1): validate all line count arguments

2021-10-10 Thread Todd C . Miller
On Sat, 09 Oct 2021 20:43:12 -0500, Scott Cheloha wrote:

> head(1) currently only validates the last count argument given.  I
> think we ought to be stricter.  You can specify the -n option an
> arbitrary number of times.

Yes, it is better to perform the check during argument processing.
OK millert@

 - todd



head(1): validate all line count arguments

2021-10-09 Thread Scott Cheloha
Hi,

head(1) currently only validates the last count argument given.  I
think we ought to be stricter.  You can specify the -n option an
arbitrary number of times.

While here, let's use the default strtonum(3) error message format.
The option-argument name is "count", not "line count".

Before:

$ head -n blah
head: line count invalid: blah
$ jot 10 | head -n blah -n 5
1
2
3
4
5

After:

$ head -n blah
head: count is invalid: blah
$ jot 10 | head -n blah -n 5
head: count is invalid: blah

ok?

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 -  1.21
+++ head.c  10 Oct 2021 01:31:29 -
@@ -48,11 +48,11 @@ static void usage(void);
 int
 main(int argc, char *argv[])
 {
+   const char *errstr;
FILE*fp;
longcnt;
int ch, firsttime;
longlinecnt = 10;
-   char*p = NULL;
int status = 0;
 
if (pledge("stdio rpath", NULL) == -1)
@@ -61,7 +61,9 @@ main(int argc, char *argv[])
/* handle obsolete -number syntax */
if (argc > 1 && argv[1][0] == '-' &&
isdigit((unsigned char)argv[1][1])) {
-   p = argv[1] + 1;
+   linecnt = strtonum(argv[1] + 1, 1, LONG_MAX, );
+   if (errstr != NULL)
+   errx(1, "count is %s: %s", errstr, argv[1] + 1);
argc--;
argv++;
}
@@ -69,21 +71,15 @@ main(int argc, char *argv[])
while ((ch = getopt(argc, argv, "n:")) != -1) {
switch (ch) {
case 'n':
-   p = optarg;
+   linecnt = strtonum(optarg, 1, LONG_MAX, );
+   if (errstr != NULL)
+   errx(1, "count is %s: %s", errstr, optarg);
break;
default:
usage();
}
}
argc -= optind, argv += optind;
-
-   if (p) {
-   const char *errstr;
-
-   linecnt = strtonum(p, 1, LONG_MAX, );
-   if (errstr)
-   errx(1, "line count %s: %s", errstr, p);
-   }
 
for (firsttime = 1; ; firsttime = 0) {
if (!*argv) {