zoukankan      html  css  js  c++  java
  • 使用getopt()处理命令行参数

    假设有一程序 testopt,其命令行选项参数有:
      -i            选项
      -l            选项
      -r           选项
      -n <值> 带关联值的选项
    则处理参数的代码如下:
    #include <stdio.h>
    #include <unistd.h>
    
    int main(int argc, char *argv[]) {
        // 选项参数 
        int opt;
        while ((opt = getopt(argc, argv, ":in:lr")) != -1) {
            switch (opt) {
            case 'i':    // 开关选项
            case 'l':
            case 'r':
                printf("option: %c
    ", opt);
                break;
            case 'n':    // 提供供了所需关联值的选项 
                printf("value of option %c: %s
    ", opt, optarg);
                break;
            case ':':    // 缺乏所需关联值的选项,选项字符在全局变量 optopt 中
                printf("option needs a value: %c
    ", optopt);
                break;
            case '?':    // 未知选项
                printf("unknown option: %c
    ", optopt);
                break;
            }
        }
        // 其余参数(非选项),由全局变量 optind 指出开始位置
        while(optind<argc) {
            printf("argument: %s
    ", argv[optind]);
            ++optind;
        }
        return 0;
    }
    输入命令行:
    $ ./testopt abc.txt -il -r -p -n18 myfile.c xyz
     
    输出:
    option: i
    option: l
    option: r
    unknown option: p
    value of option n: 18
    argument: abc.txt
    argument: myfile.c
    argument: xyz
     
    可以看到,getopt()已经把命令行参数重新排序,非选项参数都挪到了后面。
  • 相关阅读:
    [SDOI2008]递归数列
    [SCOI2008]奖励关
    [SCOI2010]幸运数字
    [ZJOI2007]矩阵游戏
    [HAOI2006]旅行
    [ZJOI2008]泡泡堂
    [BZOJ1800][Ahoi2009]fly 飞行棋
    [POJ2288]Islands and Bridges
    [LUOGU] 3959 宝藏
    [BZOJ]1029: [JSOI2007]建筑抢修
  • 原文地址:https://www.cnblogs.com/xxfcz/p/6145650.html
Copyright © 2011-2022 走看看