原文链接:https://blog.csdn.net/kunikida/article/details/8922754
程序
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int result;
opterr = 0; //使getopt不行stderr输出错误信息
while( (result = getopt(argc, argv, "abck")) != -1 )
{
switch(result)
{
case 'a':
printf("option=a, optopt=%c, optarg=%s\n", optopt, optarg);
break;
case 'b':
printf("option=b, optopt=%c, optarg=%s\n", optopt, optarg);
break;
case 'c':
printf("option=c, optopt=%c, optarg=%s\n", optopt, optarg);
break;
case '?':
printf("result=?, optopt=%c, optarg=%s\n", optopt, optarg);
break;
default:
printf("default, result=%c\n",result);
break;
}
printf("argv[%d]=%s\n", optind, argv[optind]);
}
printf("result=-1, optind=%d\n", optind); //看看最后optind的位置
for(result = optind; result < argc; result++)
printf("-----argv[%d]=%s\n", result, argv[result]);
//看看最后的命令行参数,看顺序是否改变了哈。
for(result = 1; result < argc; result++)
printf("\nat the end-----argv[%d]=%s\n", result, argv[result]);
return 0;
}
测试用例
./test -a 123 456 -b 2 -c 3 -k 4
结果:
option=a, optopt=, optarg=(null)
argv[2]=123
option=b, optopt=, optarg=(null)
argv[5]=2
option=c, optopt=, optarg=(null)
argv[7]=3
default, result=k
argv[9]=4
result=-1, optind=5
-----argv[5]=123
-----argv[6]=456
-----argv[7]=2
-----argv[8]=3
-----argv[9]=4
at the end-----argv[1]=-a
at the end-----argv[2]=-b
at the end-----argv[3]=-c
at the end-----argv[4]=-k
at the end-----argv[5]=123
at the end-----argv[6]=456
at the end-----argv[7]=2
at the end-----argv[8]=3
at the end-----argv[9]=4
程序:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
int tmp = 4;
while( (tmp = getopt(argc, argv, "abck")) != -1 )
{
printf("-%c\t", tmp);
int opt = optind ;
while( opt < argc )
{
if ( argv[opt][0] != '-' )
{
printf("%s\t", argv[opt]);
opt ++;
}
else
break;
}
printf("\n");
}
getchar();
}
测试用例:
./test -a 123 456 -b 2 -c 3 -k 4
结果:
-a 123 456
-b 2
-c 3
-k 4