经常出现 -c -p -n 等带参数的命令, Linux用getopt_long可以分解参数,如果是Windows就不能实用。
以下自己写了个参数分析函数,便于大家使用:
struct _optArg {
char szSec[8];
int nCount;
char szArgs[6][64];
int nType;
};
int args_opt_init(int argc, char * const argv[], struct _optArg *optsOut, int *pnCount)
{
int i = 0;
int nSecCount = 1;
int nCol = 0;
int mMy = 0;
if(optsOut == NULL)
{
printf("Error\n");
return 0;
}
strcpy(optsOut->szSec, "def");
for(i = 0; i < argc; i++)
{
if(strncmp(argv[i],"-",1) == 0)
{
nSecCount++;
optsOut++;
strcpy(optsOut->szSec, argv[i]+1);
//printf("SEC SAVE [%d] [%s]\n", i, optsOut->szSec);
nCol = 0;
mMy = 1;
continue;
}
strcpy(optsOut->szArgs[nCol++], argv[i]);
//printf("VALUE SAVE [%d][%s][%d]\n", i,argv[i], nCol-1);
optsOut->nCount++;
}
*pnCount = nSecCount;
return nSecCount;
}
char* args_opt_get(struct _optArg *optsOut, int nOptCnt, const char *psSec, int nIdx)
{
int i = 0;
for(i = 0; i < nOptCnt; i++)
{
if(strcmp(optsOut->szSec, psSec) == 0)
{
if(nIdx < 0)
{
return optsOut->szSec;
}
if(optsOut->nCount > nIdx)
{
return optsOut->szArgs[nIdx];
}
break;
}
optsOut++;
}
return "";
}
int getopt
int main(int argc, char ** argv)
{
int nSecCount = 0;
char *pArg = NULL;
struct _optArg opts[10] = {0};
args_opt_init(argc, argv, opts, &nSecCount);
pArg = args_opt_get(opts, nSecCount, "u", 0);
if(strcmp(pArg, "") != 0)
{
strcpy(stru_ip_info.m_strRemoteIpaddr, pArg);
pArg = args_opt_get(opts, nSecCount, "u", 1);
printf("%s\n", pArg);
pArg = args_opt_get(opts, nSecCount, "u", 2);
printf("%s\n", pArg);
nCmdType = 1;
}
return 0;
}
文 | 力卉编程
网友评论