Kunjan Patel
Kunjan Patel

Reputation: 9

getopt_long the second option gets recognised as argument of first option

int main(int argc , char *argv[])
{
    int c;
    int sock;
    struct sockaddr_in server;
    char message[1000] , server_reply[2000];
    FILE *log;
    //int cp;
    int port_no;

    while(1)
    {
        static struct option long_options[]=
        {
            {"port", required_argument, 0, 'p'},
            {"log", required_argument, 0, 'l'},
        };

        c = getopt_long(argc, argv, "p:l:",long_options,NULL);

        if(c==-1)
        {
            break;
        }
        switch (c)
        {
            case 'p':
                if (optarg)
                {
                    port_no = atoi(optarg);
                }
                else
                {
                    fprintf(stderr,"Usage --port= port number\n");
                }
                break;
            case 'l':
                if(optarg)
                {
                    log = fopen(optarg,"w");
                }
                else
                {
                    fprintf(stderr,"Usage --log= logfilename\n");
                }
                break;
            case '?':
                //fprintf(stderr,"Argument no recognised\n");
                break;
        }
    }
}

When I run ./client --port --log it recognizes --log as the port number argument, and when I run ./client --log --port, it recognizes --port as the log file argument and creates a file named --port.

Why does this happen? Isn't -- a special character in getopt_long()?

Upvotes: 0

Views: 69

Answers (1)

delta
delta

Reputation: 3818

port and log are both declared as required_argument. Thus it looks the argument behind --log, so --port is treated as the arg not option.

The proper usage would be something like ./client --port 8080 --log file.log.

Upvotes: 2

Related Questions