getopt的使用

时间:2019-02-16
本文章向大家介绍getopt的使用,主要包括getopt的使用使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

提取命令行的参数使用getopt系统函数

例子:

#include<unistd.h>
#include<iostream>
#include<getopt.h>
#include<stdlib.h>
#include<string>
using namespace std;

int main(int argc,char *argv[])
{
    const char *str = "t:l:p:";
    int opt;
    while((opt = getopt(argc,argv,str))!=-1)
    {
        switch(opt)
        {
            case 't':
            {
                int threadNum = atoi(optarg);
                cout << threadNum <<endl;
                break;
            }
            case 'l':
            {
                string logpath = optarg;
                cout << logpath << endl;
                break;
            }
            case 'p':
            {
                int port = atoi(optarg);
                cout << port << endl;
                break;
            }
        //    printf("%d %s %d\n",threadNum,logpath,port);
        }
    }
    return 0;
}

截图: