Hello,
I'm writing a program. I'd like it to be compatible with MinGW's C compiler and Linux. Right now, I'm writing the code in Linux. I'm not 100% sure MinGW has the getopt_long function or if it's just a *nix thing. Anyway, I'm having some trouble understanding this code. I've a read a bit about this but I'm still a bit confused and was hoping someone here could help. I'll post the code and then ask my question.
Code:
int do_all, do_help, do_verbose; /* flag variables */
char *myfile, *user; /* input file, user name */
struct option longopts[] = {
{ "all", no_argument, & do_all, 1 },
{ "file", required_argument, NULL, 'f' },
{ "help", no_argument, & do_help, 1 },
{ "verbose", no_argument, & do_verbose, 1 },
{ "user" , optional_argument, NULL, 'u' },
{ 0, 0, 0, 0 }
};
...
while ((c = getopt_long(argc, argv, ":ahvf:u::W;", longopts, NULL)) != –1) {
switch (c) {
case 'a':
do_all = 1;
break;
case 'f':
myfile = optarg;
break;
case 'h':
do_help = 1;
break;
case 'u':
if (optarg != NULL)
user = optarg;
else
user = "root";
break;
case 'v':
do_verbose = 1;
break;
case 0: /* getopt_long() set a variable, just keep going */
break;
#if 0
case 1:
/*
* Use this case if getopt_long() should go through all
* arguments. If so, add a leading '-' character to optstring.
* Actual code, if any, goes here.
*/
break;
#endif
case ':': /* missing option argument */
fprintf(stderr, "%s: option `-%c' requires an argument\n",
argv[0], optopt);
break;
case '?':
default: /* invalid option */
fprintf(stderr, "%s: option `-%c' is invalid: ignored\n",
argv[0], optopt);
break;
}
}
I don't really understand the val field in the struct option longopts part.
Code:
struct option longopts[] = {
{ "all", no_argument, & do_all, 1 },
{ "file", required_argument, NULL, 'f' },
{ "help", no_argument, & do_help, 1 },
{ "verbose", no_argument, & do_verbose, 1 },
{ "user" , optional_argument, NULL, 'u' },
{ 0, 0, 0, 0 }
};
My understanding is the third element determines what happens with the fourth element there. So, if I pass --all to my program, getopt_long will return 1. Is that the whole point of the case 0: and the case 1: at the bottom of the case / switch statement?