1-代码及注释
这个例程是man手册里的。
1-1 getopt_long.c
#include <stdio.h> /* for printf */
#include <stdlib.h> /* for exit */
#include <getopt.h>
/*
man 3 getopt_long
函数原型:
int getopt_long(int argc, char * const argv[],
const char *optstring,
const struct option *longopts, int *longindex);
*/
int main(int argc, char **argv)
{
int c;//c在下面作为getopt_long()的返回值
int digit_optind = 0;
while (1) {
int this_option_optind = optind ? optind : 1;
int option_index = 0;
static struct option long_options[] = {
{"add", required_argument, 0, 0 },
{"append", no_argument, 0, 0 },
{"delete", required_argument, 0, 0 },
{"verbose", no_argument, 0, 0 },
{"create", required_argument, 0, 'c'},
{"file", required_argument, 0, 0 },
{0, 0, 0, 0 }
};
printf("\noptind:%d\n", optind);
c = getopt_long(argc, argv, "abc:d:012",long_options, &option_index);
//getopt_long(argc, argv, optstring ,longopts, longindex);
//1-argc:main()函数传递过来的参数的个数
//2-argv:main()函数传递过来的参数的字符串指针数组
//3-optstring:选项字符串,告知 getopt()可以处理哪个选项以及哪个选项需要参数
// char*optstring = “ab:c::”;
// 单个字符 a 表示选项a没有参数 格式:-a即可,不加参数
// 单字符加冒号 b: 表示选项b有且必须加参数 格式:-b 100或-b100,但-b=100错
// 单字符加2冒号 c:: 表示选项c可以有,也可以无 格式:-c200,其它格式错误
//4-longopts指明了长参数的名称和属性
// struct option
// {
// const char *name;// 参数名称
// /* Has_arg不能是enum,因为有些编译器会抱怨在所有假定它是int型的代码中存在类型不匹配。 */
// int has_arg;//指明是否带有参数
// int *flag;// flag=NULL时,返回value;不为空时,*flag=val,返回0
// int val;// 用于指定函数找到选项的返回值或flag非空时指定*flag的值
// };
//5-longindex 如果 longindex 非空,
//它指向的变量将记录当前找到参数符合 longopts 里的第几个元素的描述,
//即是 longopts 的下标值
if (c == -1)//如果所有命令行选项都解析完毕,getopt_long()返回 -1;
break;//退出while(1)循环
switch (c) {
case 0:
printf("option %s", long_options[option_index].name);
if (optarg)
printf(" with arg %s", optarg);
printf("\n");
break;
case '0':
case '1':
case '2':
if (digit_optind != 0 && digit_optind != this_option_optind)
printf("digits occur in two different argv-elements.\n");
digit_optind = this_option_optind;
printf("option %c\n", c);
break;
case 'a':
printf("option a\n");
break;
case 'b':
printf("option b\n");
break;
case 'c':
printf("option c with value '%s'\n", optarg);
break;
case 'd':
printf("option d with value '%s'\n", optarg);
break;
case '?':
break;
default:
printf("?? getopt returned character code 0%o ??\n", c);
}
}
//optind 再次调用 getopt() 时的下一个 argv 指针的索引。
printf("\nargc:%d ", argc);
printf("\noptind:%d\n", optind);
if (optind < argc) {
printf("non-option ARGV-elements: ");
while (optind < argc)
printf("%s ", argv[optind++]);
printf("\n");
}
exit(EXIT_SUCCESS);
}
1-2 getopt_core.h(linux系统自带)
/* Declarations for getopt (basic, portable features only).
Copyright (C) 1989-2020 Free Software Foundation, Inc.
This file is part of the GNU C Library and is also part of gnulib.
Patches to this file should be submitted to both projects.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#ifndef _GETOPT_CORE_H
#define _GETOPT_CORE_H 1
/* This header should not be used directly; include getopt.h or
unistd.h instead. Unlike most bits headers, it does not have
a protective #error, because the guard macro for getopt.h in
gnulib is not fixed. */
__BEGIN_DECLS
/* For communication from 'getopt' to the caller.
When 'getopt' finds an option that takes an argument,
the argument value is returned here.
Also, when 'ordering' is RETURN_IN_ORDER,
each non-option ARGV-element is returned here. */
extern char *optarg;
/* Index in ARGV of the next element to be scanned.
This is used for communication to and from the caller
and for communication between successive calls to 'getopt'.
On entry to 'getopt', zero means this is the first call; initialize.
When 'getopt' returns -1, this is the index of the first of the
non-option elements that the caller should itself scan.
Otherwise, 'optind' communicates from one call to the next
how much of ARGV has been scanned so far. */
extern int optind;
/* Callers store zero here to inhibit the error message 'getopt' prints
for unrecognized options. */
extern int opterr;
/* Set to an option character which was unrecognized. */
extern int optopt;
/* Get definitions and prototypes for functions to process the
arguments in ARGV (ARGC of them, minus the program name) for
options given in OPTS.
Return the option character from OPTS just read. Return -1 when
there are no more options. For unrecognized options, or options
missing arguments, 'optopt' is set to the option letter, and '?' is
returned.
The OPTS string is a list of characters which are recognized option
letters, optionally followed by colons, specifying that that letter
takes an argument, to be placed in 'optarg'.
If a letter in OPTS is followed by two colons, its argument is
optional. This behavior is specific to the GNU 'getopt'.
The argument '--' causes premature termination of argument
scanning, explicitly telling 'getopt' that there are no more
options.
If OPTS begins with '-', then non-option arguments are treated as
arguments to the option '\1'. This behavior is specific to the GNU
'getopt'. If OPTS begins with '+', or POSIXLY_CORRECT is set in
the environment, then do not permute arguments.
For standards compliance, the 'argv' argument has the type
char *const *, but this is inaccurate; if argument permutation is
enabled, the argv array (not the strings it points to) must be
writable. */
extern int getopt (int ___argc, char *const *___argv, const char *__shortopts)
__THROW __nonnull ((2, 3));
__END_DECLS
#endif /* getopt_core.h */
2 执行结果
编译1-1中getopt_long.c,执行可执行文件即可。
根据执行结果分析代码。