Zisko
Zisko

Reputation: 105

How does getopt(3) work, and what is the 'extern' variable optarg?

I am trying to learn how to accept command line arguments and accompanying data following flags, i.e.

myprogram -sampleflag datahere

My code is here so far. getopt() throws data into a variable c, and apparently you can access optarg from outside the function it was called. How is this possible? According to the man page, my code should work! However, as you can see the output is (null).

my code:

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

int main(int argc, char *argv[]) {
    opterr = 0;
    char* cvalue = NULL;
    int c;
    char* optarg = hello;

while((c = getopt(argc, argv, "ps")) != -1){
    switch(c){
        case 'p':
            cvalue = optarg;
            printf("cvalue is : %s\n", cvalue );
            break;
        }
    }
}

my output: ($ myprogram -p test)

cvalue is : (null)

Upvotes: 5

Views: 565

Answers (1)

Matt
Matt

Reputation: 7160

From the manual:

An option character in this string can be followed by a colon (‘:’) to indicate that it takes a required argument.

So in your case your string for options should be "p:s" rather than "ps".

Upvotes: 5

Related Questions