Reputation: 1
How do I detect the user passed no arguments to a program with getopt_long? I could detect the user calling the program with no arguments by checking argc, but what about the user calling my program with just a dash?
$ my_prog -
Do I need to include this option somehow in my getopt statement?
while(ca = getopt_long(argc, argv, "abc:D:",...)
What would the function return?
Upvotes: 0
Views: 1289
Reputation: 2863
Just start your optstring with '-' character. From man getopt_long
:
If the first character of optstring is '-', then each nonoption argv-element is handled as if it were the argument of an option with character code 1
So with the optstring "-abc:D:" you can assume there were some arguments passed if you entered the while
loop.
Upvotes: 0
Reputation: 121427
You can use optind
variable to determine such arguments:
The variable optind is the index of the next element of the argv[] vector to be processed. It shall be initialized to 1 by the system, and getopt() shall update it when it finishes with each element of argv[].
For example,
for(int i = optind; i < argc; i++)
printf("Unknown argument: %s\n", argv[i]);
You can do this after argument processing to find out if there are any such unexpected arguments.
Upvotes: 1