Some programs in bin/ and usr.bin/ use the following idiom
to make sure that there are no options present:
while ((ch = getopt(argc, argv, "")) != -1)
switch (ch) {
case '?':
default:
usage();
/* NOTREACHED */
}
if (argc != optind) {
usage();
/* NOTREACHED */
}
Why is this better then simply checking that (argc == 1)?
Below is a diff to logname as an example.
(Remove the pointless locale while there.)
Jan
Index: logname.c
===================================================================
RCS file: /cvs/src/usr.bin/logname/logname.c,v
retrieving revision 1.9
diff -u -p -r1.9 logname.c
--- logname.c 9 Oct 2015 01:37:08 -0000 1.9
+++ logname.c 12 Oct 2016 08:38:49 -0000
@@ -32,7 +32,6 @@
#include <stdio.h>
#include <stdlib.h>
-#include <locale.h>
#include <unistd.h>
#include <err.h>
@@ -44,23 +43,11 @@ main(int argc, char *argv[])
int ch;
char *p;
- setlocale(LC_ALL, "");
-
if (pledge("stdio", NULL) == -1)
err(1, "pledge");
- while ((ch = getopt(argc, argv, "")) != -1)
- switch (ch) {
- case '?':
- default:
- usage();
- /* NOTREACHED */
- }
-
- if (argc != optind) {
+ if (argc != 1)
usage();
- /* NOTREACHED */
- }
if ((p = getlogin()) == NULL)
err(1, NULL);