运行带参程序的时候,传参不正常。
int ch;
while ((ch = getopt(argc, argv, "p")) != -1)
{
switch (ch)
{
case 'p':
if (optarg)
nPort = atoi(optarg);
break;
default:
printf("Erroe option: %c\n", ch);
return -1;
}
}
调试发现,运行 xxx -p 10000的时候,optarg为空,所以nPort不能获取到值。
跟进代码里,发现,getopt第三个参数optstring必须是:结尾
#include "getopt/getopt.h"
getopt (int argc, char *const *argv, const char *optstring)
上面使用
while ((ch = getopt(argc, argv, "p")) != -1)
是错误的
改成这样
int ch;
while ((ch = getopt(argc, argv, "p:")) != -1)
{
switch (ch)
{
case 'p':
if (optarg)
nPort = atoi(optarg);
break;
default:
printf("Erroe option: %c\n", ch);
return -1;
}
}