(C语言)Linux中对程序接收输入参数

1.程序代码

short_options:短参数,后面跟一个冒号为有参数,后面跟两个为参数可有可没有

long_options:长参数,第二项为0为无参数,1为有参数,2为参数可有可无,第四项为对应的短参数

#include<stdio.h>
#include<stdlib.h>
#include<getopt.h>
#include<sys/time.h>

#define APP_VERSION "V1.0.0 ("__DATE__" "__TIME__")"

int main(int argc, char* argv[])
{
    printf("Program Version: %s\n", APP_VERSION);
    printf("Program Start!\n");

    int next_option;

    const char* const short_options="abcd:e:f:g::";
    const struct option long_options[] = 
    {
        {"aaaa", 0, NULL, 'a'},
        {"bbbb", 0, NULL, 'b'},
        {"cccc", 0, NULL, 'c'},
        {"dddd", 1, NULL, 'd'},
        {"eeee", 1, NULL, 'e'},
        {"ffff", 1, NULL, 'f'},
        {"gggg", 2, NULL, 'g'}
    };

    do
    {
        next_option = getopt_long(argc, argv, short_options, long_options, NULL);
        switch(next_option)
        {
            case 'a': 
                {
                    printf("a received!\n");
                }break;
            case 'b':
                {
                    printf("b received!\n");
                }break;
            case 'c':
                {
                    printf("c received!\n");
                }break;
            case 'd':
                {
                    printf("d received! Para:%s\n", optarg);
                }break;
            case 'e':
                {
                    printf("e received! Para:%sWn", optarg);
                }break;
            case 'f':
                {
                    printf("f received! Para:%s\n", optarg);
                }break;
            case 'g':
                {
                    printf("g received! Para:%s\n", optarg);
                }break;
            case '?':
                {
                    printf("unknown word!\n");
                    break;
                }break;
        }
        //printf("%d\n",next_option);
    }
    while(next_option != -1);

    printf("Program Closed!\n");
    exit(0);
}

2.运行结果

200419_Ljb3_1425762.png

END

转载于:https://my.oschina.net/Tsybius2014/blog/288454

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值