C语言之getopt 命令行参数获取

#include 
#include 

int main(int argc, char** argv)
{
	int ch;
	int opterr = 0;
	while((ch = getopt(argc, argv, "a:b::dcewf")) != -1)
	{
        printf("optind:%d\n", optind);
        printf("optarg:%s\n", optarg);
        printf("ch is %c\n", ch);
		switch(ch)
        {
            case 'a':
                printf("option a:'%s'\n", optarg);
                break;
            case 'b':
                printf("option b:'%s'\n", optarg);
                break;
            case 'c':
                printf("option c\n");
                break;
            default:
                printf("other %c\n", ch);
        } 
        
	}
}
./main -atest1 -btest2 -d -c -e
optind:2
optarg:test1
ch is a
option a:'test1'
optind:3
optarg:test2
ch is b
option b:'test2'
optind:4
optarg:(null)
ch is d
other d
optind:5
optarg:(null)
ch is c
option c
optind:6
optarg:(null)
ch is e
other e

 

你可能感兴趣的:(C)