分类: C/C++
2014-01-01 23:20:42
1 全局变量 optind 的作用
它的值表示将要分析argv中的,如果要重新扫描一个命令行参数选项,那么将给值设置为1(设置为0 不起作用)
2 getopt 的返回值
如果能找到一个选项,并且该选项值出现在optstr字符串内,则返回该选项的字符
如果所有的选项都处理完了,则返回-1
如果能找到一个选项,但是该选项没有出现在optstr字符串内,则返回'?'字符
如果没有给出选项的参数,那么当 optstr字符串的第一个字符为':', 则返回‘:', 否则返回'?'字符
3 optopt 变量(类型 int)
保存没有在optstr字符串上的选项
4 struct option {
const char *name; // 长选项的名字
int has_arg; // 是否带有选项参数, no_argument, required_argument
int *flag; // 一般都设置为 NULL, 则函数返回 val值
int val;
}
struct option options[] = {
{"name", required_argument, NULL, 'n'},
{"age", required_argument, NULL, 'a' },
{0,0,0.0}
}
实例代码
点击(此处)折叠或打开
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <getopt.h>
- int main(int argc ,char *argv[])
- {
- int c;
- while ((c = getopt(argc, argv, ":a:b")) != -1)
- {
- switch (c)
- {
- case 'a':
- fprintf(stderr, "[INFO]###### a option is given, option argument is :%s\n", optarg);
- break;
- case 'b':
- fprintf(stderr, "[INFO]###### b option is given\n");
- break;
- case '?':
- fprintf(stderr, "[ERROR]###### not such %c option in the optstr \n", optopt);
- case ':':
- fprintf(stderr, "[ERROR]###### you must give option %c an argument .\n", optopt);
- break;
- }
- }
- return (0);
- }
点击(此处)折叠或打开
- #include <stdio.h>
- #include <stdlib.h>
- #include <getopt.h>
- #include <string.h>
- #include <errno.h>
- int main(int argc, char *argv[])
- {
- char command[] = "vde2-net 21749 2.4 42.8 11769352 10595956 ? Sl May24 69:26 /usr/local/infobright-4.0.7-x86_64/bin/mysqld --defaults-file=/etc/my-ib.cnf --basedir=/usr/local/infobright-4.0.7-x86_64 --datadir=/home/ib_iee/data --user=mysql --log-queries-not-using-indexes --log-error=/home/ib_iee/data/bh.err --pid-file=/home/ib_iee/data/debRDTest1.pid --socket=/tmp/mysql-ib.sock --port=5029";
- char *ib_argv[1024] = { 0 };
- int ib_argc = 0;
- char *saveptr ;
- char *str = command;
- int i;
- opterr = 0; // prevent the error message
- while (1)
- {
- char *a_argv = strtok_r(str, " ", &saveptr);
- if (a_argv == NULL)
- {
- break;
- }
- ib_argv[ib_argc] = malloc(1024);
- strncpy(ib_argv[ib_argc], a_argv, 1024);
- ib_argc++;
- str = NULL;
- }
- const char *ib_base_dir = NULL;
- const char *ib_data_dir = NULL;
- while (1)
- {
- static struct option options [] = {
- {"basedir", required_argument, NULL, 'b'},
- {"datadir", required_argument, NULL, 'd'},
- {NULL, 0, NULL, 0}
- };
- int c ;
- int longindex;
- c = getopt_long_only(ib_argc, ib_argv, "", options, &longindex);
- if (c == -1)
- {
- break;
- }
- switch (c)
- {
- case 'd':
- ib_data_dir = optarg;
- break;
- case 'b':
- ib_base_dir = optarg;
- break;
- }
- }
- if (!((int)ib_data_dir & (int)ib_base_dir))
- {
- fprintf(stderr, "[ERROR]#################### service is not running .!\n");
- exit(-1);
- }
- fprintf(stderr, "[INFO] ################# basedir = %s \n", ib_base_dir);
- fprintf(stderr, "[INFO] ################# datadir = %s \n", ib_data_dir);
- cleanup:
- for (i = 0; i < ib_argc; ++i)
- {
- free(ib_argv[i]);
- }
- return 0;
- }