Question

I am currently trying to understand the basis of parsing and wrote that code. The code is very simple. I just want to write a program that is able to make different jobs with different commends. I use linux and I start code by way of bash commends.

That code just prints "n is printed" with -n commmend and cant print "t is printed" with -t commend. I get "Option requires an argument --'t'" error. How to handle it?

My second question is the difference between "nt: " and "n:t:". When I tried second one, I got nothing printed as a result.

Thanks in advance.

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

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

    opterr = 0;


    while ((opt = getopt(argc, argv, "nt:")) != -1) {
        switch (opt) {
        case 'n':
            printf("n is printed");
            break;
        case 't':
            printf("t is printed");
            break;

     }
    }
}
Was it helpful?

Solution

When you put ':' after a character, the function expects one (or more) arguments, each arguments preceded by a space.
So you have to type :

yourprogram -t yourargument 

To get your(s) argument(s) you have to declare :

extern char * optarg;  

which will contain the arguments.

Wish it could help you,

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