`
topzhujia
  • 浏览: 57002 次
  • 性别: 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.

分享到:
评论

相关推荐

    64位linux 编译c提示gnu/stubs-32.h:No such file or directory的解决方法

    在64位Linux系统下编译C语言程序时,可能会出现gnu/stubs-32.h文件不存在的错误,主要是因为缺少32位兼容包的原因。今天,我们就来探讨解决这个问题的方法。 首先,让我们了解问题的出现原因。在编译C语言程序时,...

    mipsel-linux-as: not found 是因为系统是64位的,按照以下文档安装几个包即可解决

    编译uboot时出现/bin/sh: 1: /opt/buildroot-gcc342/bin/mipsel-linux-as: not found 是因为系统是64位的,按照以下文档安装几个包即可解决

    Debian GNU / Linux:安装和使用指南Debian GNU/Linux: Guide to Installation and Usage

    面向不熟悉Debian GNU / Linux的读者,假定他们没有GNU / Linux或其他类似Unix的系统的先验知识。

    学习Debian GNU / LinuxLearning Debian GNU/Linux

    根据提供的文件信息,我们将深入探讨Debian GNU/Linux的相关知识点,主要关注新Linux用户以及桌面Linux应用程序的需求。 ### Debian GNU/Linux简介 Debian GNU/Linux是一种免费的操作系统,它基于GNU工具集和Linux...

    GNU / Linux高级管理GNU/Linux Advanced Administration

    涵盖高级GNU / Linux系统管理。 学生将学习如何安装,配置和优化GNU / Linux操作系统以及使用最广泛的计算机服务。

    gnu/linux编程指南源码

    《GNU/Linux编程指南》是一本深入探讨GNU/Linux操作系统下编程实践的宝贵资源,它涵盖了从基本的编程概念到高级的系统级编程技术。这个源码集合对于那些希望在GNU/Linux环境中提升编程技能或者想要深入了解操作系统...

    Debian GNU/Linux 安装手册

    ### Debian GNU/Linux 安装手册知识点详析 #### 一、Debian GNU/Linux 简介 **1.1 什么是Debian?** Debian 是一个由社区支持的开源操作系统,以其高度稳定性和安全性著称。它遵循自由软件基金会制定的自由软件...

    Dragora GNU/Linux-Libre:独立的GNU / Linux-Libre发行版-开源

    Dragora是GNU / Linux操作系统的完整而可靠的发行版,它是完全免费的软件。 Dragora基于简单和优雅的概念,几乎可以用于任何目的(台式机,工作站,服务器,开发等)运行。 目标读者是有兴趣了解有关GNU / Linux发行...

    Dragora GNU/Linux-Libre:一个独立的 GNU/Linux-Libre 发行版-开源

    Dragora 是一个完整可靠的 GNU/Linux 操作系统发行版,它是完全免费的软件。 Dragora 建立在简单和优雅的概念之上,它几乎可以用于任何目的(桌面、工作站、服务器、开发等)。 目标受众是有兴趣了解更多关于 GNU/...

    深入GNU/Linux编程技术

    本书《GNU/Linux Application Programming, Second Edition》由M. Tim Jones撰写,是关于GNU/Linux系统下应用程序开发的全面指南。书中首先介绍了UNIX和GNU/Linux的历史,以及Linux发行版的概况。接着,作者深入探讨...

    debian (Debian GNU/Linux下的小康生活)

    ### Debian GNU/Linux 知识点概述 #### 一、Debian GNU/Linux 概览 **1.1 GNU/Linux** **1.1.1 GNU 项目** - **起源与发展**: GNU 项目始于 1983 年,由 Richard Stallman 发起。该项目旨在创建一套完全自由的...

    透视Debian GNU/Linux.pdf

    《透视Debian GNU/Linux》这本书深入探讨了Debian GNU/Linux操作系统,这是一款在全球范围内深受开发者和高级用户喜爱的Linux发行版。Debian以其开源、免费和社区驱动的特点,吸引了大量忠实用户。它并非由商业实体...

    GNU Linux Application Programming

    The wide range of applications available in GNU/Linux includes not only pure applications, but also tools and utilities for the GNU/Linux environment. GNU/Linux Application Programming takes a ...

    gnu/linux嵌入式快速编程一书的完整源代码

    在GNU/Linux嵌入式开发领域,编程涉及到许多关键知识点,特别是在使用像BeagleBone Black这样的开发板时。这本书“GNU/Linux嵌入式快速编程”提供了丰富的实践指导,其完整的源代码是深入理解这一领域的宝贵资源。...

    GNU/Linux Basic operating system

    GNU/Linux 操作 介绍 英文版 Joaquín López Sánchez-Montañés Sofia Belles Ramos Roger Baig Viñas Francesc Aulí Llinàs 1. Introduction 2. Basic concepts and commands 3. Knoppix workshop 4. GNU/...

    GNU/Linux Rapid Embedded Programming

    An annotated guide to program and develop GNU/Linux Embedded systems quickly About This Book Rapidly design and build powerful prototypes for GNU/Linux Embedded systems Become familiar with the ...

    GUN/LINUX环境编程(第2版) 源代码

    1. **C语言基础**:GNU/Linux编程主要基于C语言,因此熟悉C语言的基本语法、数据类型、控制结构、函数和指针是必不可少的。书中可能通过源代码展示了如何使用这些概念来构建系统级程序。 2. **标准输入/输出与文件...

    GNU/Linux 编程指南(第二版)

    GNU/Linux 编程指南(第二版),Linux下 C语言的必看书!

    GNU/Linux Command−Line Tools Summary

    ### GNU/Linux命令行工具概览 #### 一、概述 GNU/Linux 命令行工具概览是一份由 GNU 开源组织提供的官方学习文档,它为用户提供了关于 GNU/Linux 系统下各种命令行工具的详尽介绍。这份文档不仅适合初学者了解基本...

    《Debian GNU/Linux高级应用大全》简介.pdf

    《Debian GNU/Linux高级应用大全》简介.pdf

Global site tag (gtag.js) - Google Analytics