Question

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)
Was it helpful?

Solution

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".

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