`
iwindyforest
  • 浏览: 233642 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Command Line Options: getopt_long() Learning Note

阅读更多

Definition

 

#include <getopt .h>

extern char *optarg

extern int optind , opterr , optopt ;

int getopt_long (int argc , char * const argv [],
                  const char *optstring ,
                  const struct option *longopts , int *longindex );

 

optarg : if an option takes an argument, the pointer will point at that argument.

 

optind : is the index of the next element to be processed in argv .
The system initializes this value to 1 .  The caller can reset it to 1 to restart scanning of the same argv, or when scanning a new argument vector.

 

After all command-line options have been parsed, the optind value could be equal to argc or less than argc . If optind < argc, means there are verbose arguments left which cannot be parse by getopt ().

 

opterr, optopt : If getopt () does not recognize an option character, it prints an error message to stderr , stores the character in optopt , and returns '? '. The calling program may prevent the error message by setting opterr to 0 .

 

Parameters

 

argc : the count of input parameters, which passed to the main() function on program invocation.

 

argv : the array of input parameters, which passed to the main() function on program invocation.

 

optstring : a character string containing the valid short options, each a single letter. An option that requires an argument is followed by a colon. For your program, the string ho:v indicates that
the valid options are -h, -o, and -v, with the second of these options followed by an argument.

 

       if a character is followed by a colon, means the option requires an argument.

       For example: ho:v    , means option o requires an argument, used as: "-o arg ".

 

       if a character is followed by two colons, means the option takes an optional argument.

       For example: ho::v    , means option o takes an optional argument, used as: "-oarg ", or "-o ".

       we should notice that if we use "-o arg " under the circumstances, "arg " will not be parsed as 

       the argument of option "o ".

 

longopts : a pointer to the first element of an array of struct option declared in <getopt.h > as

       struct option {
               const char *name;
               int         has_arg;
               int        *flag;
               int         val;
           };

       The meanings of the different fields are:

       name   is the name of the long option.

       has_arg

              is:

              no_argument (or 0) if the option does not take an argument;
              required_argument (or 1) if the option requires an argument;
              optional_argument (or 2) if the option takes an optional argument.

       flag    specifies how results are returned for a long option.  If flag is NULL ,
              then getopt_long() returns val.  (For example, the calling program may
              set val to the equivalent short option character.)  Otherwise,
              getopt_long() returns 0, and flag points to a variable which is set to
              val if the option is found, but left unchanged if the option is not
              found.

       val    is the value to return, or to load into the variable pointed to by
              flag.

 

longindex : If it is not NULL , it points to a variable which is set to the index of the long option relative to longopts .

 

 

Return Value

 

If an option was successfully found, then getopt() returns the option character. If all command-line options have been parsed, then getopt() returns -1 .  If getopt() encounters an option character that was not in optstring, then '?' is returned.  If getopt() encounters an option with a missing argument, then the return value depends on the first character in optstring: if it is ':', then ':' is returned; otherwise '?' is returned.

 

After all command-line options have been parsed, the optind value could be equal to argc or less than argc . If optind < argc, means there are verbose arguments left which cannot be parse by getopt (). Under the circumstances, these verbose arguments can be feached from the changed(by getopt() ) array argv from argv[ind] to argv[argc-1] .

 

 

Sample Code

 

NOTE: the following code is written under the stardard of C99, use blow command to compile:

[280047@SHNI145 code] $ gcc -Wall -std=gnu99 -g getopt.c -o getopt

 

#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>

/* The name of this program. */
const char* program_name;

/* Prints usage information for this program to STREAM (typically stdout or stderr),
 * and exit program with EXIT_CODE. Does not return. */
void print_usage(FILE* stream, const int exit_code, const char* error_message) {
    if(error_message != NULL) {
        fprintf(stream, "%s \n", error_message);
    }
    fprintf(stream, "Usage: %s options [inputfile ...]\n", program_name);
    fprintf(stream, 
            "   -h         --help              Display this usage information. \n"
            "   -f <file>  --output filename   Write output to file. \n"
            "   -o<Arg>    --optional          Print optional argument. \n");
    exit(exit_code);
}

void print_argument(const int option, const char* argument) {
    if(argument != NULL) {
        printf("%c == %s \n", option, argument);
    }
}

void print_verbose_arguments(const int argc, char* const* argv) {    
    for(int i=optind; i<argc; i++) {
        printf("verbose argument: %s\n", argv[i]);
    }    
}

void reset_optind(void)
{
    optind = 1;
}

void parse_parameters(const int argc, char* const* argv, const char* const optstring, const struct option* longopts) {    
    int next_option = 0;
    if(argc <= 1) {
        print_usage(stdout, 0, NULL);
    } else {    
        reset_optind();
        while(next_option = getopt_long(argc, argv, optstring, longopts, NULL), next_option != -1) {
            if(next_option == 'h') {
                print_usage(stdout, 0, NULL);
            } else if(next_option == 'f') {
                print_argument(next_option, optarg);
            } else if(next_option == 'o') {
                print_argument(next_option, optarg);
            } else if(next_option == '?') {
                print_usage(stderr, 1, NULL);
            } 
        } 
        print_verbose_arguments(argc, argv);
    }

}

int main(int argc, char** argv)
{
    /* A string listing valid short options letters. */
    const char* const short_options = "hf:o::";
    /* An array descriping valid long options. */
    const struct option long_options[] =    {
        { .name="help",     .has_arg=no_argument,           .flag=NULL,   .val='h' },
        { .name="output",   .has_arg=required_argument,     .flag=NULL,   .val='f' },
        { .name="option",   .has_arg=optional_argument,     .flag=NULL,   .val='o' },
        { .name=NULL,       .has_arg=no_argument,           .flag=NULL,   .val=0   }   };    
    /* Remember the name of the program, to incorporate in messages.
     * The name is stored in argv[0]. */
    program_name = argv[0];

    parse_parameters(argc, argv, short_options, long_options);

    return 0;
}


 

Test

 

[280047@SHNI145 code] $ ./getopt -h
Usage: ./getopt options [inputfile ...]
   -h         --help              Display this usage information.
   -f <file>  --output filename   Write output to file.
   -o<Arg>    --optional          Print optional argument.

[280047@SHNI145 code] $ ./getopt -f file
f == file

[280047@SHNI145 code] $ ./getopt -oArg
o == Arg

[280047@SHNI145 code] $ ./getopt -o arg
verbose argument: arg

[280047@SHNI145 code] $ ./getopt 11 22 33 44 -f 55 -o 66
f == 55
verbose argument: 11
verbose argument: 22
verbose argument: 33
verbose argument: 44
verbose argument: 66

[280047@SHNI145 code] $ ./getopt -f 11 22 33 44 -f 55 -o 66
f == 11
f == 55
verbose argument: 22
verbose argument: 33
verbose argument: 44
verbose argument: 66

[280047@SHNI145 code] $ ./getopt --output 11 22 33 44 -option=55 -o 66
f == 11
o == ption=55
verbose argument: 22
verbose argument: 33
verbose argument: 44
verbose argument: 66

[280047@SHNI145 code] $ ./getopt --output=11 22 33 44 --option=55 -o 66
f == 11
o == 55
verbose argument: 22
verbose argument: 33
verbose argument: 44
verbose argument: 66

 

 

reference

 

Advance Linux Programming

http://www.kernel.org/doc/man-pages/online/pages/man3/getopt.3.html

 

 

 

 

 

0
0
分享到:
评论

相关推荐

    getopt.h getopt getopt_long

    win10 vs2019下的 getopt及getopt_long getopt/getopt_long函数是GNU C中的函数

    getopt.h getopt.c getopt getopt_long 字符串 命令行

    `getopt` 是一个库函数,用于解析程序启动时的命令行选项,而 `getopt_long` 是 `getopt` 的扩展版本,增加了对长选项的支持,使得命令行参数的使用更加灵活和易读。 `getopt.h` 是头文件,包含了 `getopt` 函数的...

    windows下的getopt/getopt_long等函数,vs2010实测可用

    GNU libc提供了getopt和getopt_long用于解析命令行参数,使用方便,但是windows环境没有提供。故将GNU libc提供的源码稍加修改,整理出了windows下可用的getopt和getopt_long。

    windows 版本 getopt_long

    windows 版本 getopt_long ,从GLIBC移植过来,解析命令行参数. 命令行参数可以分为两类,一类是短选项,一类是长选项,短选项在参数前加一杠"-",长选项在参数前连续加两杠"--",如下表(ls 命令参数)所示,其中-a,...

    getopt源码下载及getopt_long源码下载

    本文将深入探讨`getopt`及其扩展`getopt_long`的使用,同时结合提供的代码示例进行解析。 `getopt`函数的基本形式如下: ```c int getopt(int argc, char *const argv[], const char *optstring); ``` `argc`是...

    getopt.h getopt.c getopt_long 文件和函数说明

    `getopt` 函数是C标准库的一部分,通常用于解析命令行参数,而`getopt_long` 是一个扩展功能,提供更方便的方式来处理长选项。 `getopt.h` 文件包含了 `getopt` 函数的声明。这个函数主要用于处理命令行参数,它...

    getopt和getopt_long在Linux操作系统下解析命令

    `getopt`和`getopt_long`函数是C语言标准库中用于解析命令行参数的两个重要工具,它们能帮助我们方便地获取和处理用户在执行程序时传递的参数。 `getopt`函数是最基础的命令行参数解析函数,它按照一定的顺序(通常...

    详细解析命令行的getopt_long()函数

    `getopt_long()` 是一个在 C 语言编程中用于解析命令行选项的函数,它特别支持长选项形式,常用于 Linux 和类 Unix 系统下的应用程序。这个函数可以帮助程序员更方便地处理用户在命令行中输入的各种选项和参数。 ##...

    getopt及getopt_long.rar

    在Linux系统编程中,`getopt`和`getopt_long`是两个非常重要的命令行选项解析函数,它们帮助开发者处理程序启动时的命令行参数。这两个函数由GNU C库提供,广泛应用于各种C语言编写的命令行工具和应用程序中。在...

    linux解析命令行选项getopt_long用法解读.docx

    Linux中的`getopt_long`函数是用来解析命令行选项的一个标准工具,它可以帮助程序员方便地处理命令行参数。本文将深入探讨`getopt_long`的用法及其相关知识点。 首先,`getopt_long`函数通常在编写需要处理命令行...

    BRLOptionParser:getopt_long(3)的简短包装。 解析Objective-C的命令行选项

    (和getopt_long_only(3))的简短包装。 安装 使用 : # Podfile pod 'BRLOptionParser' , '~&gt; 0.3.1' 例子 // main.m # import int main ( int argc, const char * argv[]) { @autoreleasepool { NSString *...

    getopt windows实现

    你可以考虑使用`std::parse_command_line`或`boost::program_options`等更现代的库来解析命令行参数,它们提供了更强大且更易用的API。 4. **自定义实现**:如果你的项目不需要跨平台,或者只需要简单的命令行解析...

    c-getopt-long 使用手册

    在C编程中,`getopt()` 和 `getopt_long()` 是两个非常重要的函数,用于解析命令行选项。它们主要用于处理程序启动时用户输入的一系列参数,例如 `-h`(帮助)或 `-o`(带有参数的选项)。这些函数是C标准库的一部分...

    基于mjpg-streamer-r63的源码分析之:基础知识详细解释[二].pdf

    Linux系统提供了许多函数用于解析命令行参数,其中getopt_long函数和getopt_long_only函数是较为常用的两个函数。这两个函数的作用是帮助程序员处理输入的命令行参数,并解析出程序需要的参数值。本文将详细介绍...

    getopt多参数解析函数具体分析命令行参数解析

    `getopt()`函数是C语言中用于解析命令行参数的标准函数,主要应用于Unix/Linux系统,也可以在其他支持C语言的环境中使用。它简化了对带有选项和参数的命令行输入的处理,使得程序能够优雅地解析和理解用户提供的...

    getopt_mb_uni_src.zip

    下面是一个简单的C代码示例,展示了如何在Windows下使用移植后的getopt: ```c #include "getopt.h" int main(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "ho:")) != -1) { ...

    getopt源码,32,64库

    `getopt`是一个在许多Unix-like操作系统中广泛使用的命令行参数解析函数库。它使得程序能够解析命令行选项,按照标准的Unix风格处理 `-` 开头的单字符选项和 `--` 开头的长选项。这个库对于编写接受命令行参数的程序...

Global site tag (gtag.js) - Google Analytics