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这样带有选项的命令执行

原文地址:https://www.cnblogs.com/wiessharling/p/4056348.html