[C]使用getopt()来parsing command line的参数
时间:2014-07-24 09:23 来源: 我爱IT技术网 作者:山风
在Linux底下我们经常会使用'-'来设置一些参数,比如说grep使用-n来设置显示搜索到的行数。
- grep -n "test" ./*
当我们自己写Linux程序时有没有比较快的方法能parsing这些参数呢?Linux底下有个好用的function叫getopt(),他可以帮住我们来parsing这些参数。要使用getopt()必须要include unistd.h,以下是一个范例:
- #include <stdio.h>
- #include <unistd.h>
- int main(int argc, char* argv[])
- {
- char ch;
- int count;
- while ((ch = getopt(argc, argv, "d:t")) != EOF) {
- switch (ch) {
- case 'd':
- printf("-d %s\r\n", optarg);
- break;
- case 't':
- printf("-t\r\n");
- break;
- default:
- fprintf(stderr, "Unknown option: '%s'\n", optarg);
- return 1;
- }
- }
- //skip the option we read
- argc -= optind;
- argv += optind;
- for (count = 0; count < argc; count++) {
- puts(argv[count]);
- }
- return 0;
- }
- sway@mac$ gcc getopt.c -o getopt
- sway@mac$ ./getopt -d test -t apple banana
- -d test
- -t
- apple
- banana
这边要注意的是第8行getopt()的第三个参数"d:t"。d后面的:表示-d之后需要再指定一个参数,而此参数可在optarg中取得。t后面没有:号表示之后不需要再指定参数。
第27行的puts会把不属于-d -t的剩下所有参数都印出来,optind其实就是前面while循环处理到第几个参数的index。
- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
