Вопрос

I have possible just stirred me blind on the code below, but I cannot get getopt_long to pass the argument "maska" which is ARG_MASK0.

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

typedef char Char;
typedef int Int;
typedef unsigned char UInt8;

enum eArgs {
    ARG_MOTION=258, //258
    ARG_MASK0,  //259
    ARG_MASK1,  //260
    ARG_NO_TTY  //261
};


void main(Int argc, Char *argv[])
{
    const Char shortOptions[] = "h";
    const struct option longOptions[] = {
        {"motion",           required_argument, NULL, ARG_MOTION},
        {"maska",             required_argument, NULL, ARG_MASK0},
        {"maskb",             required_argument, NULL, ARG_MASK1},
        {"notty",            no_argument,       NULL, ARG_NO_TTY},
        {"help",             no_argument,       NULL, 'h'},
        {0, 0, 0, 0}
    };

    Char    *end;
    Int     index;
    Int     c,i;
    UInt8   mask[10];

    fprintf(stderr, "argc=%i\n", argc);
    for(i=1; i < argc; i++) {
        fprintf(stderr, "argv[%i]=%s\n", i,argv[i]);
    }

    for (;;) {
        c = getopt_long(argc, argv, shortOptions, longOptions, &index);

        fprintf(stderr,"c=%i\n", c);

        if (c == -1) {
            break;
        }
    }
}

I compile the code on Ubuntu as:

gcc test_parseargs.c -o main

And run it as:

./main --motion --maska=0 --maskb=1 --notty

Get the output:

argc=5
argv[1]=--motion
argv[2]=--maska=0
argv[3]=--maskb=1
argv[4]=--notty
c=258
c=260
c=261
c=-1

What is wrong with my code?

Это было полезно?

Решение

Problem is with your arguments

{"motion",           required_argument, NULL, ARG_MOTION}, //code

./main --motion --maska=0 --maskb=1 --notty

argument for motion is missing. Try below.

./main --motion=1 --maska=0 --maskb=1 --notty

In the previous run, --maska=0 is considered as argument for motion

Другие советы

The code is correct.

You don't provide an argument to --motion. Therefore, --maska=0 is used as the argument to --motion and the remaining arguments are shown correctly as

c=260
c=261
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top