`
topzhujia
  • 浏览: 57357 次
  • 性别: Icon_minigender_1
  • 来自: 重庆
社区版块
存档分类
最新评论

GNU/Linux C language: Command Options Parsing

阅读更多

1.GNU/Linux Command-Line Conventions

Almost all GNU/Linux programs obey some conventions about how command-line arguments are interpreted.The arguments that programs expect fall into two categories: options (or flags) and other arguments. Options modify how the program behaves, while other arguments provide inputs (for instance, the names of input files).

Options come in two forms:

Short options consist of a single hyphen and a single character (usually a lowercase or uppercase letter). Short options are quicker to type.

Long options consist of two hyphens, followed by a name made of lowercase and uppercase letters and hyphens. Long options are easier to remember and easier to read (in shell scripts, for instance).

Usually, a program provides both a short form and a long form for most options it supports, the former for brevity and the latter for clarity. For example, most programs understand the options -h and --help, and treat them identically. Normally, when a program is invoked from the shell, any desired options follow the program name immediately. Some options expect an argument immediately following. Many programs, for example, interpret the option --output foo to specify that output of the program should be placed in a file named foo. After the options, there may follow other command-line arguments, typically input files or input data.

For example, the command ls -s / displays the contents of the root directory.The -s option modifies the default behavior of ls by instructing it to display the size (in kilobytes) of each entry.The / argument tells ls which directory to list.The --size option is synonymous with -s, so the same command could have been invoked as ls --size /.

The GNU Coding Standards list the names of some commonly used command-line options. If you plan to provide any options similar to these, it’s a good idea to use the names specified in the coding standards.Your program will behave more like other programs and will be easier for users to learn.

2.Using getopt_long

Parsing command-line options is a tedious chore. Luckily, the GNU C library provides a function that you can use in C and C++ programs to make this job somewhat easier (although still a bit annoying).This function, getopt_long, understands both short and long options. If you use this function, include the header file <getopt.h>.

Suppose, for example, that you are writing a program that is to accept the three options shown in Table 2.1.

Table 2.1 Example Program Options

Short Form

Long Form

Purpose

-h

--help

Display usage summary and exit

-o filename

--output filename

Specify output filename

-v

--verbose

Print verbose messages

In addition, the program is to accept zero or more additional command-line arguments, which are the names of input files.

To use getopt_long, you must provide two data structures.The first is 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.

To specify the available long options, you construct an array of struct option elements. Each element corresponds to one long option and has four fields. In normal circumstances, the first field is the name of the long option (as a character string, without the two hyphens); the second is 1 if the option takes an argument, or 0 otherwise; the third is NULL; and the fourth is a character constant specifying the short option synonym for that long option.The last element of the array should be all zeros.You could construct the array like this:

const struct option long_options[] ={

     { "help", 0, NULL, 'h'},

     {"output", 1, NULL, 'o'},

     { "verbose", 0, NULL, 'v'},

     {NULL, 0, NULL, 0}

};

 

You invoke the getopt_long function, passing it the argc and argv arguments to main, the character string describing short options, and the array of struct option elements describing the long options.

Each time you call getopt_long, it parses a single option, returning the shortoption letter for that option, or –1 if no more options are found.

Typically, you’ll call getopt_long in a loop, to process all the options the user has specified, and you’ll handle the specific options in a switch statement.

If getopt_long encounters an invalid option (an option that you didn’t specify as a valid short or long option), it prints an error message and returns the character ? (a question mark). Most programs will exit in response to this, possibly after displaying usage information.

When handling an option that takes an argument, the global variable optarg points to the text of that argument.

After getopt_long has finished parsing all the options, the global variable optind contains the index (into argv) of the first nonoption argument. Listing 2.2 shows an example of how you might use getopt_long to process your arguments.

Listing 2.2 (getopt_long.c) Using getopt_long

#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 the program with EXIT_CODE. Does not

 return. */

void print_usage(FILE* stream, int exit_code) {

     fprintf(stream, "Usage: %s options [ inputfile ... ]\n", program_name);

     fprintf(stream, " -h --help Display this usage information.\n"

         " -o --output filename Write output to file.\n"

         " -v --verbose Print verbose messages.\n");

     exit(exit_code);

}

/* Main program entry point. ARGC contains number of argument list

 elements; ARGV is an array of pointers to them. */

int main(int argc, char* argv[]) {

     int next_option;

     /* A string listing valid short options letters. */

     const char* const short_options = "ho:v";

     /* An array describing valid long options. */

     const struct option long_options[] = { { "help", 0, NULL, 'h' }, {

              "output", 1, NULL, 'o' }, { "verbose", 0, NULL, 'v' }, { NULL, 0,

              NULL, 0 } /* Required at end of array. */

     };

     /* The name of the file to receive program output, or NULL for

      standard output. */

     const char* output_filename = NULL;

     /* Whether to display verbose messages. */

     int verbose = 0;

     /* Remember the name of the program, to incorporate in messages.

      The name is stored in argv[0]. */

     program_name = argv[0];

     do {

         next_option

                   = getopt_long(argc, argv, short_options, long_options, NULL);

         switch (next_option) {

         case 'h': /* -h or --help */

              /* User has requested usage information. Print it to standard

               output, and exit with exit code zero (normal termination). */

              print_usage(stdout, 0);

         case 'o': /* -o or --output */

              /* This option takes an argument, the name of the output file. */

              output_filename = optarg;

              break;

         case 'v': /* -v or --verbose */

              verbose = 1;

              break;

         case '?': /* The user specified an invalid option. */

              /* Print usage information to standard error, and exit with exit

               code one (indicating abnormal termination). */

              print_usage(stderr, 1);

         case -1: /* Done with options. */

              break;

         default: /* Something else: unexpected. */

              abort();

         }

     } while (next_option != -1);

     /* Done with options. OPTIND points to first nonoption argument.

      For demonstration purposes, print them if the verbose option was

      specified. */

     if (verbose) {

         int i;

         for (i = optind; i < argc; ++i)

              printf("Argument: %s\n", argv[i]);

     }

     /* The main program goes here. */

     return 0;

}

Using getopt_long may seem like a lot of work, but writing code to parse the command-line options yourself would take even longer.The getopt_long function is very sophisticated and allows great flexibility in specifying what kind of options to accept. However, it’s a good idea to stay away from the more advanced features and stick with the basic option structure described.

分享到:
评论

相关推荐

    python3.6.5参考手册 chm

    PEP 389: The argparse Module for Parsing Command Lines PEP 391: Dictionary-Based Configuration For Logging PEP 3106: Dictionary Views PEP 3137: The memoryview Object Other Language Changes ...

    kind-linux-amd64

    kind-linux-amd64

    第一章-操作系统概述习题及答案.doc

    第一章-操作系统概述习题及答案.doc

    第5章PLC基础知识.ppt

    第5章PLC基础知识.ppt

    TMS FNC WX Pack v1.7.2.4 FS.7z

    TMS FNC WX Pack v1.7.2.4 完整源码版 TMS FNC WX Pack 是一款由 TMS Software 提供的通用 Delphi & C++ Builder 组件集,能够将独特的 Web 技术融入到 VCL、FMX、LCL 和 Web 核心应用程序中。 功能 - 条形码和二维码生成:TTMSFNCWXBarcode 和 TTMSFNCWXQRCode 组件可以生成 QR/条码图像,并提供 100 多种不同类型的条形码。 - 摄像头功能:TTMSFNCWXCamera 组件可利用设备摄像头扫描 QR 或条码。 - HTML 编辑:TTMSFNCWXHTMLMemo 组件用于查看和编辑 HTML 格式文本,包括表格、图像等。 - PDF 查看:TTMSFNCWXPDFViewer 是一个本地或在线 PDF 查看器,带有可选的缩略图列表和交互式工具栏。 - 视频播放:TTMSFNCWXVideoPlayer 组件可播放各种格式的本地或在线视频。 - JSON 格式化:TTMSFNCWXJSONFormatter 组件以格式化的方式显示 JSON,并可自定义外观。 - 文本转语音:TTMSFNCWXSpeechSynthesis 组件可将文本转换为语音,并提供多种操作系统原生语音选择。 - OCR 功能:TTMSFNCWXOCR 组件可扫描图像中的可读文本,并以多种语言输出。 - 文档生成:TTMSFNCWXDocx 组件可动态生成带有页眉、页脚、表格等的 .docx 文件。 - 数学公式编辑:TTMSFNCMathEditor 组件可渲染和编辑数学公式,并提供自定义虚拟键盘。

    dmarm_description.zip

    dmarm_description.zip

    北京市RJ办公区供热运行策略毕设.rar

    1.版本:matlab2014/2019a/2024a 2.附赠案例数据可直接运行。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    ESP32中文相关资料+Arduino实验 例程源码.zip

    ESP32中文相关资料+Arduino实验 例程源码,ESP32中文相关资料+Arduino实验 例程源码,ESP32中文相关资料+Arduino实验 例程源码.zip

    使用Mie理论计算雷达截面积(RCS)Matlab代码 matlab代码.rar

    1.版本:matlab2014/2019a/2024a 2.附赠案例数据可直接运行。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    罗特曼透镜设计与HFSS链接 matlab代码.rar

    1.版本:matlab2014/2019a/2024a 2.附赠案例数据可直接运行。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    三阶、五阶与七阶多项式函数

    在机器人技术中,运动控制是实现机器人精确、高效运动的关键环节,而轨迹规划则是运动控制的核心部分。其目的是设计出一条平滑、连续且符合机器人动力学约束的路径,使机器人能够从起点平稳地移动到目标点。其中,多项式插值是一种常用的轨迹规划方法,可根据给定的起点和终点条件,生成满足要求的曲线轨迹。三次、五次和七次多项式是轨迹规划中常见的类型,其阶数决定了轨迹的灵活性和复杂性。 三次多项式(Cubic Polynomial)是最简单的连续可微多项式,形式为 f(t)=at 3 +bt 2 +ct+d。它常用于简单任务,能够确保通过起点、终点以及两个中间点的切线方向,共四个控制点。三次多项式轨迹规划简单且计算成本低,但可能无法满足复杂运动需求。 五次多项式(Quintic Polynomial)增加了自由度,形式为 f(t)=at 5 +bt 4 +ct 3 +dt 2 +et+f。它可以确保通过起点、终点、两个中间点及其切线方向,共六个控制点。这使得五次多项式在保持平滑的同时,能更好地适应路径曲率变化,适用于复杂轨迹规划。 七次多项式(Seventh Polynomial)提供了更高的灵活性,可以处理复杂路径规划问题。它有七个控制点,可精确控制起点、终点及五个中间点的切线方向。七次多项式通常用于高精度任务,如精密装配或医疗手术机器人,能够精细控制速度和加速度变化。 文件名 seventh.m、cubic.m 和 quintic.m 可能是用 MATLAB 编写的函数,分别用于实现七次、三次和五次多项式的轨迹规划算法。这些函数通常接受起点、终点坐标和时间参数,计算多项式系数,并输出随时间变化的位置、速度和加速度数据。 在实际应用中,选择多项式次数需综合考虑以下因素:路径平滑性,更高阶多项式可减少加速度突变,降低机械应力;计算复杂性,阶数越高计算量越大,可能影响实时性能;控制精度,更高阶多项

    电子商务物流第二版教案第9章.ppt

    电子商务物流第二版教案第9章.ppt

    光储并网直流微电网Simulink仿真:MPPT与混合储能系统提升电能质量 · 逆变器双闭环控制 (2025年)

    内容概要:本文介绍了光储并网直流微电网的Simulink仿真模型及其关键技术。首先,通过MPPT(最大功率点跟踪)算法实现了光伏阵列的最大功率输出,确保了能量的有效利用。其次,构建了由蓄电池和超级电容组成的混合储能系统,分别应对高频、中频和低频功率变化,提升了电能质量和储能系统的寿命。此外,采用二阶低通滤波法对光伏输出功率进行抑制,进一步优化了电能质量。最后,逆变器采用基于电网电压的双闭环控制策略,确保了逆变器输出的稳定性。文中还展示了部分Simulink模型代码示例,帮助读者更好地理解和实现该模型。 适合人群:从事电力电子技术、新能源系统设计的研究人员和技术人员,尤其是对微电网仿真感兴趣的读者。 使用场景及目标:适用于需要深入了解光储并网直流微电网的工作原理和仿真的研究人员和技术人员。目标是通过Simulink仿真模型,掌握MPPT、混合储能系统、二阶低通滤波法和逆变器双闭环控制的关键技术和实现方法,为实际应用提供理论支持。 其他说明:文中提供的代码示例仅为简化版本,在实际建模过程中还需考虑更多细节,如模型参数的详细设置和仿真环境的配置。

    电脑基础知识及办公软件使用.pptx

    电脑基础知识及办公软件使用.pptx

    第7章电子商务物流.ppt

    第7章电子商务物流.ppt

    Zztxtesttest.txt

    Zztxtesttest.txt

Global site tag (gtag.js) - Google Analytics