Question

I wrote (copied and pasted from Google and simplified) a C program to use getopt to print out the values of the arguments passed in from the Unix command line.

From Unix command line:

./myprog -a 0 -b 1 -c 2

My C code is:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    int i;

    while ((i = getopt(argc, argv, "abc")) != -1) {
        switch (i) {
            case 'a': 
               printf("A = %s\n", optarg);
               break;

            case 'b': 
               printf("B = %s\n", optarg);
               break;

            case 'c': 
               printf("C = %s\n", optarg);
               break;

            default:
                break;
        }
    }

    return 0;
}    

I want to program to print out each of the values passed e.g.

A = 0
B = 1
C = 2

However it is not printing out anything at all.

Was it helpful?

Solution

You forget about ":" after any option with argument. If you will change one line

while ((i = getopt(argc, argv, "a:b:c:")) != -1) {

you will get working variant.

Read properly man 3 getopt, it said about third argument of getopt that

… optstring is a string containing the legitimate option characters. If such a character is followed by a colon, the option requires an argument, so getopt() places a pointer to the following text in the same argv-element, or the text of the following argv-element, in optarg. 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. …

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top