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()已经把命令行参数重新排序,非选项参数都挪到了后面。
  • 相关阅读:
    api自动化工具集成metersphere
    gitlab+github使用记录
    docker基本操作
    linux指标分析
    python的break和continue
    linux基本性能指标语法
    jmeter标准流程设置
    postman
    jmeter本地启动
    对浮动的一些个人理解
  • 原文地址:https://www.cnblogs.com/xxfcz/p/6145650.html
Copyright © 2011-2022 走看看