• getopt 分析命令行参数 -n -t 1


    在Linux中,我们常常用到 ls -l 等等之类带有选项项的命令,下面,让我们用C++来实现该类似的命令。

    在实现之前,首先,我们来介绍一下一个重要函数:getopt()

    表头文件 #include<unistd.h>
    定义函数 int getopt(int argc,char * const argv[ ],const char * optstring);
     
    函数说明:
    用来分析命令行参数。参数 argc argv 是由 main() 传递的参数个数和内容。
    参数 optstring为选项字符串, 告知 getopt()可以处理哪个选项以及哪个选项需要参数,如果选项字符串里的字母后接着冒号“:”,则表示还有相关的参数,全域变量optarg 即会指向此额外参数。
    如果在处理期间遇到了不符合optstring指定的其他选项getopt()将显示一个错误消息,并将全域变量optarg设为“?”字符,如果不希望getopt()打印出错信息,则只要将全域变量opterr设为0即可。
     
    C++实现例子:
    int main(int argc, char **argv)
    {
        int flag = 0;
        int type = 0;
        int opt;
        while(1)
        {
            opt = getopt(argc, argv, "nt:");
            if(opt == '?')
                exit(EXIT_FAILURE);
            else if(opt == -1)
                break;
    
            switch(opt)
            {
                case 'n':
                    /*printf("AAAAAAAAA
    ");*/
                    flag |= IPC_NOWAIT;
                    break;
                case 't':
                    /*printf("BBBBBBBb
    ");
                    int n = atoi(optarg);
                    printf("n = %d
    ", n);*/
                    type = atoi(optarg);
                    break;
            }
        }
    }

    编译完之后,我们可以使用:./a.out   -n -t 1这样带有选项的命令执行

  • 相关阅读:
    python+requests+re匹配抓取猫眼上映电影信息
    Qt 5.12 LTS 部署
    Apache 日志记录相关设置
    php curl 相关知识
    Apache缓存相关配置
    Apache开启GZIP 压缩网页
    Apache 相关 mod_rewrite ,RewriteCond,{HTTP_HOST}
    Andriod you must restart adb and eclipse
    JDK 环境变量的配置
    http 协议详解
  • 原文地址:https://www.cnblogs.com/wiessharling/p/4056348.html
Copyright © 2020-2023  润新知