您的位置:首页 > 运维架构

parse命令行的函数简介:getopt和getopt_long (x264中用到了这两个函数)

2012-12-14 21:37 393 查看
       命令行是用户与程序打交道的一个重要途径,为了让用户使用方便,程序员需要设计出相应的函数对命令行进行解析. 在linux等系统中, getopt函数就是干这个的,下面摘录Wikipedia中的资料:(看英语的感觉就是爽啊!)

 

      A long standing issue with
command line programs was how to specify options; early programs used many ways of doing so, including single character options (
-a
), multiple options specified together (
-abc
is equivalent to
-a -b -c
), multicharacter options (
-inum
), options with arguments (
-a arg
,
-inum 3
,
-a=arg
), and different prefix characters (
-a
,
+b
,
/c
).

     The getopt
function was written to be a standard mechanism that all programs could use to parse

command-line options so that there would be a common interface that everyone could depend on. As such, the original authors picked out of the variations support for single character options, multiple options specified together, and options with arguments
(
-a arg
or
-aarg
), all controllable by an option string.

      getopt dates back to at least 1980and was first published by
AT&T at the 1985 UNIFORUM conference in Dallas, Texas, with the intent for it to be available in the public domain.Versions of it were subsequently picked up by other flavors of Unix (BSD
4.3, Linux, etc.). It is specified in the
POSIX.2 standard as part of the
unistd.h
header file. Derivatives of getopt have been created for many

programming languages to parse command-line options.

 

        A GNU extension,
getopt_long, allows parsing of more readable, multicharacter options, which are introduced by two dashes instead of one. The choice of two dashes allows multicharacter options (
--inum
) to be differentiated from single character
options specified together (
-abc
). The GNU extension also allows an alternative format for options with arguments:
--name=arg
.
      getopt is not a system independent function. The implementation of
getopt in GNU C Library does permute the contents of the argument vector as it scans, so that eventually all the non-option arguments are at the end. On the contrary, the implementation of
getopt in BSD C Library does not permute the argument vector and returns -1 if it encounters a non-option argument.

 

      在Windows中可以用getopt_long么?当然可以,x264中用到的getopt_long就可以再Windwos下的VC6.0中运行. 详细情况可以参考x264中的用法,真的狠强大.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: