Linux C解析命令行参数代码

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://latelee.blog.csdn.net/article/details/81200755

背景

Linux下解析main函数参数,使用getopt,依赖头文件:#include <unistd.h>

代码如下:

static char g_deviceid[32] = {0};

std::string g_serverIP = "172.18.18.18";
static int g_serverPort = 8888;

void PrintHelp(char* prog)
{
    printf("%s usage.\n", prog);
    printf("eg:\n");
    printf("%s -i 172.18.18.18 -p 8888 -s 123456789\n", prog);
    printf("-i: ip address, default: 172.18.18.18\n");
    printf("-p: port number, default: 8888\n");
    printf("-s: serial number, default: 123456789\n");

}
void ParseArg(int argc, char *argv[])
{
    int ch = 0;

    strcpy(g_deviceid, "123456789");

    if (argc == 2)
    {
        if (!strcmp(argv[1], "?") ||
            !strcmp(argv[1], "--help") ||
            !strcmp(argv[1], "-h"))
        {
            PrintHelp(argv[0]);
            exit(0);
        }
    }

    while ((ch = getopt(argc, argv, "i:p:s:")) != -1)
    {
        switch (ch)
        {
        case 'i':
            g_serverIP = optarg;
            break;
        case 'p':
            g_serverPort = atoi(optarg);
            break;
        case 's':
            memcpy(g_deviceid, optarg, 32);
            break;
        case '?':
        default:
            PrintHelp(argv[0]);
            exit(0);
            break;
        }
    }
}

李迟 2018.7.25 中午

展开阅读全文

没有更多推荐了,返回首页