c/c++ main参数处理

abloz 2010-11-30
2010-11-30

http://abloz.com
2010.11.30

#include <getopt.h>
#include <unistd.h>
extern char *optarg;

char *usage = 
"Usage: ./program [-w web_listen_port] [-c com_listen_port]n";

void printusage ()
{
    printf ("%s", usage);
    exit (-1);
}

void printproblem(char* problem)
{
    printf ("%sn", problem);
    printusage();
}
#define LISTEN_WEBPORT 4000
#define LISTEN_COMMPORT 5000
int main(int argc, char* argv[])
{

    int ret = 0;
    char c;
    short web_port = LISTEN_WEBPORT;
    short com_port = LISTEN_COMMPORT;

    while ( (c = getopt(argc,argv,"w:c:")) >= 0)
    {
        switch (c)
        {
        case 'w':
            web_port = atoi(optarg);
            break;
        case 'c':
            com_port = atoi(optarg);
        default:
            printusage();
            break;
        }
    }
}


如非注明转载, 均为原创. 本站遵循知识共享CC协议,转载请注明来源