Looking at the linux manual for getopt at
http://man7.org/linux/man-pages/man3/getopt.3.html , and also looking at an example
https://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html .
1. Why not have line 10 with a with a single colon?
Two colons mean an option takes an optional arg; if there is
text in the current argv-element (i.e., in the same word as the
option name itself, for example, "-oarg"), then it is returned in
optarg, otherwise optarg is set to zero. This is a GNU extension. |
The double colon appears to invite complications.
2. We can see that the option flag is the output of getopt, "opt" in your case, which is fine. You forgot to make use of the special variable
optarg . See the example for reference. I also suspect your input may have spaces, which obviously messes w/ argument parsing altogether.
3. Missing break in your cases. Always break each case unless you intentionally want stuff to fall through.
4. I suggest to just make a second option for the second table, since you're into getopt anyway.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "k.h"
#define KXVER 3
static const char *optString="tu:";
int main(int argc, char *argv[]){
int opt;
char table1[30]; // t option
char table2[30]; // u option
// Variables to make sure both flags are specified
int tflag = 0;
int uflag = 0;
while( (opt=getopt(argc,argv,optString)) !=-1){
switch(opt){
case 't':
tflag = 1;
strcpy(table1, optarg);
break;
case 'u':
uflag = 1;
strcpy(table2, optarg);
break;
default:
printf("Usage: myprogram -t <table1> -u <table2>\n");
return 0;
}
}
if (!tflag && !uflag)
{
printf("Both -t and -u options are required\n");
return 2;
}
printf("table 1 is %s and table 2 is %s\n", table1, table2);
return 0;
}
|
See also (from the example) how they check for bad arguments with the special variable
optind, which auto-updates with getopt. They have a for loop to cycle through anything else the user might have (erroneously) added and prints out the issue "Non-argument ...".