Linux C解析命令行参数代码

背景

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

代码如下:

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 中午

你可能感兴趣的:(GNU/Linux)