Hi all,
I am working on a program that will take command line options and work with a file. The program usage is like this:
program -a -b --linelength=12 filename
Note that the "12" can be any number, but it's a required argument for the option "linelength".
My problem is, if I omit the linelength argument and the filename comes next, then I don't get the "option requires an argument" error, but rather the getopt tries to use the filename as the argument, effectively resulting in this:
program -a -b --linelength=filename
Then, of course, because there is no filename, that generates an error.
I am sure I'm doing something wrong or missing something, because the code should be "smart enough" to avoid this. Any ideas?
Here's (hopefully) the relevant part:
// parse arguments
while ((opt = getopt_long (argc, argv, optstr, lopts, (int *)(0))) != EOF)
{
switch (opt) {
case 'c': {
colors = 1;
break;
}
case 'h': {
return show_help();
}
case 'i': {
ignore_case = 1;
break;
}
case 'l': {
lineLength = strtol (optarg, (char **) (0), 10);
break;
}
case 'm': {
mode = maximized;
lineLength = 0;
break;
}
case 's': {
mode = bySector;
break;
}
case '?': {
if (optopt == 'l') {
fprintf (stderr, "option -%c requires an argument\n", optopt);
return 1;
}
}
default: {
break;
}
}
}
if (optind < argc)
{
fileName = argv[optind];
}
Thanks!