getopt函数,命令行解析

getopt函数

函数功能:用来解析命令行参数,参数argc和argv分别代表参数个数和内容,跟main()函数里的命令行参数一样

函数所在头文件:#include<unistd.h>

函数原型定义:int getopt(int argc, char* const argv[ ], const char *optstring )

参数optstring: 为选项字符串,告知getopt可以处理那个选项以及哪个选项需要参数,如果选项字符串里的字母后接着冒号:“:”,则表示还有相关的参数,全域变量optarg即会指向此额外参数,如果在处理期间遇到了不符合optstring指定的其他选项,getopt()将会显示一个错误消息,并将全局域变量设置为“?”字符,将全局域变量opterr设置为0则将不会打印出错信息。
参数optarg:指向当前选项参数的指针

参数optind:再次调用getopt时的下一个argv指针索引

参数optopt:表示最后一个未知选项


#include "head.h"  // 头文件在这里哦,三个;

int main(int argc, char **argv) {
    int opt;
    while((opt = getopt(argc, argv, "ab:c::"))) {
        switch(opt) {
            case 'a':
            printf("opt a found!\n");
            printf("ind = %d\n", optind);

            break;
            case 'b':
            printf("opt b found!\n");
            printf("ind = %d\n", optind);
            printf("arg for b = %s\n",optarg);
            break;
            case 'c':
            printf("opt  c found!\n");
            printf("ind = %d\n", optind);
            printf("arg for c = %s\n",optarg);
            break;
            default:
            fprintf(stderr,"Usage : %s -a -b barg -c[carg]!\n", argv[0]);
            exit(1);
        }
    }  

    return 0;
}
1. ./a.out -a -b -c -c123  [0] //索引:0 1 2 3 4 5
opt a found!
ind = 2 //找到a时a被解析,跳向下一个索引输出;
opt b found!
ind = 4 // -c 为b的参数,会被解析,跳向下一个索引并输出;
arg for b = -c
opt  c found!
ind = 5
arg for c = 123
Usage : ./a.out -a -b barg -c[carg]!

2. ./a.out -a -b -c123     [1] // 索引:0 1  2 3 
opt a found!
ind = 2 // 找到a时a被解析,跳向下一个索引输出;
opt b found!
ind = 4 // -c123 为b 的参数被解析,跳向下一索引;
arg for b = -c123
Usage : ./a.out -a -b barg -c[carg]!



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值