C语言解析命令行参数

来源:互联网 发布:人族捏脸数据导入图 编辑:程序博客网 时间:2024/05/24 05:11

最近在读《LPBE》,学习了getopt函数,写了个小程序,练练手,记录如下:

#include <stdio.h>#include <stdlib.h>#include <unistd.h>int oc;char* b_opt_arg;int main(int argc, char** argv){while ((oc = getopt(argc, argv, "ab:cd:")) != -1){switch (oc){case 'a':printf("option a\n");break;case 'b':printf("option b: %s\n", optarg);                break;case 'c':printf("option c\n");                break;case 'd':printf("option d:%d\n", atoi(optarg));                break;default:printf("unknown options\n");exit(EXIT_FAILURE);}}exit(EXIT_SUCCESS);}

 

getopt函数的第三个参数表示可以接收的option字符串,如上例可以接收-a/-b/-c/-d四个option,其中b和d后面跟冒号,代表可以有option argument,测试如下:

./a.out -a -b "Hello" -c -d '123'

打印结果如下:

option a

option b:Hello

option c

option d:123


 

 

原创粉丝点击