Linux下启动参数例子
可以输入启动参数。不过我觉得optarg在getopt.h定义有点过于生硬。虽说是C的标准做法,但是是否能传入一个指针进去更为好些?
虽说有C的写法,但是我还是比较喜欢一些C++的特性,于是一般这么用,在这里记录一下。以便以后查阅。#include <getopt.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//add by freeeyes
//支持长命名,可以任意添加
static struct option long_options[] = {
{ "help", no_argument, NULL, 'h' },
{ "version", required_argument,NULL, 'v' },
{ "index", required_argument,NULL, 'i' },
{ "run", required_argument,NULL, 'r' },
{ "args", required_argument,NULL, 'a' },
{ NULL, 0, NULL, 0}
};
//短命名
static char short_options[] = "hv:i:r:a:";
struct _ProcessArgs
{
intnIndex;
bool blIsRun;
intnVersion;
char szArgText;
_ProcessArgs()
{
nIndex = 0;
nVersion = 0;
blIsRun = false;
szArgText = '\0';
}
void display()
{
printf("nIndex=%d.\n", nIndex);
if(blIsRun == true)
{
printf("blIsRun is true.\n");
}
else
{
printf("blIsRun is false.\n");
}
printf("nVersion=%d.\n", nVersion);
printf("szArgText=%s.\n", szArgText);
}
};
static void HelpCommand()
{
printf("**************************************.\n");
printf(" -h, --help : this help.\n");
printf(" -v, --version : this version.\n");
printf(" -i, --index : this index.\n");
printf(" -r, --run : this run.\n");
printf(" -a, --args : this args.\n");
printf("**************************************.\n");
}
static int get_options(int argc, char **argv, struct _ProcessArgs *pProcessArgs)
{
int nRet = -1;
for (;;)
{
nRet = getopt_long(argc, argv, short_options, long_options, NULL);
if (nRet == -1)
{
//没有更多的命令了
break;
}
switch (nRet)
{
case 'h':
HelpCommand();
break;
case 'v':
pProcessArgs->nVersion = atoi(optarg);
break;
case 'i':
pProcessArgs->nIndex = atoi(optarg);
break;
case 'r':
if(strcmp(optarg, "true") == 0)
{
pProcessArgs->blIsRun = true;
}
else
{
pProcessArgs->blIsRun = false;
}
break;
case 'a':
sprintf(pProcessArgs->szArgText, "%s", optarg);
break;
}
}
}
int main(int argc, char **argv)
{
_ProcessArgs* pProcessArgs = new _ProcessArgs();
get_options(argc, argv, pProcessArgs);
pProcessArgs->display();
delete pProcessArgs;
return 0;
}编译:
g++ -o Testarg Testarg.cpp
运行:
./Testarg -h
输出:
**************************************.
-h, --help : this help.
-v, --version : this version.
-i, --index : this index.
-r, --run : this run.
-a, --args : this args.
**************************************.
nIndex=0.
blIsRun is false.
nVersion=0.
szArgText=.
运行:
./Testarg -h -v 10 -i 11 -r true -a freeeyes
结果:
**************************************.
-h, --help : this help.
-v, --version : this version.
-i, --index : this index.
-r, --run : this run.
-a, --args : this args.
**************************************.
nIndex=11.
blIsRun is true.
nVersion=10.
szArgText=freeeyes.
页:
[1]