使用getopt函数对windows命令行程序参数解析
getopt()是libc的标准函数,很多语言中都能找到它的移植版本。
// -b -p "c:\input" -o "e:\test\output"
bool bBinary = false;
char szPath[MAX_PATH] = {0};
char szOput[MAX_PATH] = {0};
int c = 0;
while ((c = getopt(argc, argv, CMD_PARAMETER_String)) != -1)
{
switch (c)
{
case 'b':
bBinary = true;
break;
case 'p':
{
memcpy(szPath, optarg, strlen(optarg));
}
break;
case 'o':
{
memcpy(szOput, optarg, strlen(optarg));
}
break;
case ' ':
break;
default:
printf (" getopt returned character code %c ", (char)c);
}
}
getopt()的核心是一个类似printf的格式字符串的命令行参数描述串,如上的"bp:o:"定义了b, p,o三个命令行参数,其中,b不需要参数,p和o需要跟参数。