c语言库函数getopt:用于解析main函数输入

目录

1.引言

2.getopt库函数

3.getopt的使用demo


1.引言

c语言的main函数的形式,一般为

int main(int argc, char* argv[[])

假如编译程序生产的可执行程序为target。则终端控制台运行时输入的一般形式如下

./target -选项1 参数1 -选项2 参数2。。。

argc为输入控制台的以空格分隔后的字符串的个数,argv为选项字符串的数组,其具体的数值,一般为空格分隔后的字符串数组。

2.getopt库函数

功能
getopt() 方法是用来分析命令行参数的,该方法由 Unix 标准库提供

头文件
<unistd.h> 
函数模型
int getopt(int argc, char * const argv[], const char *optstring);
extern char *optarg;
extern int optind, opterr, optopgetopt 

入力参数:
argc:通常由 main 函数直接传入,表示参数的数量
argv:通常也由 main 函数直接传入,表示参数的字符串变量数组
optstring:一个包含正确的参数选项字符串,用于参数的解析。
例如 “abc:”,其中 -a,-b 就表示两个普通选项,-c 表示一个必须有参数的选项,因为它后面有一个冒号
外部变量
optarg:如果某个选项有参数,这包含当前选项的参数字符串
optind:argv 的当前索引值
opterr:正常运行状态下为 0。非零时表示存在无效选项或者缺少选项参数,并输出其错误信息
optopt:当发现无效选项字符时,即 getopt() 方法返回 ? 字符,optopt 中包含的就是发现的无效选项字符

3.getopt的使用demo

#include<stdio.h>
#include<unistd.h>

int main(int argc, char* argv[])
{
    int ret = 0;
    printf("argc:%d\n",argc);
    printf("argv:%s\n",argv[0]);
    const char* optString = "abc:";
    while((ret = getopt(argc, argv, optString)) != -1)
    {
        printf("getopt's ret is a:%c\n",(char)ret);
        switch (ret)
        {
            case 'a':
                printf("getopt's ret is a:%s\n",optarg);
                break;
            case 'b':
                printf("getopt's ret is b:%s\n",optarg);
                break;
            case 'c':
                printf("getopt's ret is c:%s\n",optarg);
                break;
            default:
                break;
        }
    }
    return 0;
}

ubuntu系统下的编译命令

gcc string_demo.cpp -o string_demo

编译成功后运行

./string_demo -a 1 -b 2 -c 5

log结果如下

root@xuehaiyang:/mnt/hgfs/99_github/cpp_demo# ./string_demo -a 1 -b 2 -c 5
argc:7
argv:./string_demo
getopt's ret is a:a
getopt's ret is a:(null)
getopt's ret is a:b
getopt's ret is b:(null)
getopt's ret is a:c
getopt's ret is c:5

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青草地溪水旁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值