getopt()算法详解

原文链接:https://blog.csdn.net/kunikida/article/details/8922754
程序

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
 
int main(int argc, char **argv)
{
    int result;
 
    opterr = 0;  //使getopt不行stderr输出错误信息
 
    while( (result = getopt(argc, argv, "abck")) != -1 )
    {
           switch(result)
          {
               case 'a':
                   printf("option=a, optopt=%c, optarg=%s\n", optopt, optarg);
                   break;
              case 'b':
                   printf("option=b, optopt=%c, optarg=%s\n", optopt, optarg);
                   break;
              case 'c':
                   printf("option=c, optopt=%c, optarg=%s\n", optopt, optarg);
                   break;
              case '?':
                    printf("result=?, optopt=%c, optarg=%s\n", optopt, optarg);
                    break;
              default:
                   printf("default, result=%c\n",result);
                   break;
           }
        printf("argv[%d]=%s\n", optind, argv[optind]);
    }
    printf("result=-1, optind=%d\n", optind);   //看看最后optind的位置
 
    for(result = optind; result < argc; result++)
         printf("-----argv[%d]=%s\n", result, argv[result]);
 
 //看看最后的命令行参数,看顺序是否改变了哈。
    for(result = 1; result < argc; result++)
          printf("\nat the end-----argv[%d]=%s\n", result, argv[result]);
    return 0;
}

测试用例

./test -a 123 456 -b 2 -c 3 -k 4

结果:

option=a, optopt=, optarg=(null)
argv[2]=123
option=b, optopt=, optarg=(null)
argv[5]=2
option=c, optopt=, optarg=(null)
argv[7]=3
default, result=k
argv[9]=4
result=-1, optind=5
-----argv[5]=123
-----argv[6]=456
-----argv[7]=2
-----argv[8]=3
-----argv[9]=4

at the end-----argv[1]=-a

at the end-----argv[2]=-b

at the end-----argv[3]=-c

at the end-----argv[4]=-k

at the end-----argv[5]=123

at the end-----argv[6]=456

at the end-----argv[7]=2

at the end-----argv[8]=3

at the end-----argv[9]=4

程序:

#include <stdio.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
    int tmp = 4;
   
    while( (tmp = getopt(argc, argv, "abck")) != -1  )
    {
           
           printf("-%c\t", tmp);
           int opt = optind ;
           while( opt < argc )
           {
                  if ( argv[opt][0] != '-' )
                  {
                       printf("%s\t", argv[opt]);
                       opt ++;
                  }
                  else
                      break;
           }
           printf("\n");
    }
    getchar();
}

测试用例:

./test -a 123 456 -b 2 -c 3 -k 4

结果:

-a        123       456
-b        2
-c        3
-k        4

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值