Today I came across a function [getopt] by accident.
It is very useful to parse command-line arguments with this tool!

Here is:

#inlcude <unistd.h>
int getopt(int argc, char * const argv[], const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;

#include <getopt.h>
int getopt_long(int argc, char * const argv[],
                         const char *optstring,
                         const struct option *longopts, int *longindex);
int getopt_long_only(int argc, char * const argv[],
                         const char *optstring,
                         const struct option *longopts, int *longindex);

Explain for getopt():

  • Arguments argc and argv are the argument count and array as passed to the main() function.
  • optstring is the options set. One semicolon following a character means that character need a argument, and two semicolon mean the argument is optional.
  • optind is the index of the next element to be processed in argv. The system initializes this value to 1. You can reset it to 1 to restart scanning of the same argv, or when scanning a new argument vector.
  • If there are no more option characters, getopt() returns -1 or, it will keep return the ASCII of the current character.
  • optarg points to the argument string of one option if that option has argument following.

E.g.

#include <unistd.h>
#include <stdio.h>
#include <stdbool.h> // bool type
/* Macro Definition */
#define NO 0
#define YES 1
#define OK 0
#define ERROR -1

/* Structure for Global Arguments */
struct GlbArgs_t{
    bool version;
    bool help;
    char *number;
    char *type;
}GlbArgs;

/* Options allowed */
static const char *optString = "n:t::vh?";
/* Usage */
static const char *usage = "Usage: \n"
                           "-n\n"
                           "-tx (x=type-name) \n"
                           "-v\n"
                           "-h -?\n";
/* Initialize Global Argument structure */
void InitGlbArg()
{
    GlbArgs.version = NO;
    GlbArgs.help    = NO;
    GlbArgs.number  = NULL;
    GlbArgs.type    = NULL;
}

int main(int argc, char **argv)
{
    int opt = 0; // option

    InitGlbArg();

    while((opt = getopt(argc, argv, optString)) != ERROR){
        switch(opt){
        case 'n':
            GlbArgs.number = optarg;
            printf("Number: %s\n", GlbArgs.number);
            break;
        case 't':
            GlbArgs.type = optarg;
            printf("Type: %s\n", GlbArgs.type);
            break;
        case 'v':
            GlbArgs.version = YES;
            printf("Version: 1.0\n");
            break;
        case 'h':
        case '?':
            printf("%s", usage);
            break;
        default:
            break;
        }
    }

    return OK;
}
  • Learn a lot from here
  • For more details, refer to [man 3 getopt] (LInux)

Use getopt() & getopt_long() to Parse Arguments的更多相关文章

  1. parse arguments in bash

    There are lots of ways to parse arguments in sh. Getopt is good. Here's a simple script that parses ...

  2. 函数参数选项的处理getopt getopt_long getopt_long_only

    转载:http://blog.chinaunix.net/uid-20321537-id-1966849.html   在头文件中int getopt(int argc,char *argv[], c ...

  3. C语言命令行解析函数:getopt/getopt_long

    命令行工具下的参数选项有两种,长选项和短选项.短选项以-开头,后面跟单个字母:长选项以--开头,后面可跟多个字母. 一. getopt() 1.功能:解析命令行短选项参数 2.函数原型: #inclu ...

  4. 命令行解析函数:getopt/getopt_long

    参考: http://blog.csdn.net/zhangyang0402/article/details/5671410 http://www.cnblogs.com/gnuhpc/archive ...

  5. getopt getopt_long

    getopt_long支持长选项的命令行解析,使用man getopt_long,得到其声明如下: #include <getopt.h> int getopt_long(int argc ...

  6. 命令行参数解析:getopt,getopt_long

    #include <unistd.h> int getopt(int argc, char * const argv[], const char *optstring); extern c ...

  7. getopt() getopt_long()函数手册[中文翻译]

    getopt()函数 getopt_long函数 函数原型(function prototype) #include <unistd.h> int getopt(int argc, cha ...

  8. apue编程之getopt ,getopt_long使用方法以及实例

    1.getopt 1.1 函数定义 int getopt(int argc, char * const argv[], const char *optstring);#include <unis ...

  9. 命令行解析函数:getopt_long、getopt

    一.前言 在学习一些项目代码时,尤其涉及到命令行传参的代码,经常遇到getopt相关的函数,对这一类函数可以说是既陌生又熟悉.陌生是因为不知道它是干啥的,熟悉呢,是因为经常遇到.于是乎在追踪了多天ip ...

随机推荐

  1. 【javascript实例】 具有立体效果的图片浏览器

    此实例,直接粘贴代码即可运行,当然图片的路径不要忘记改了. 此实例是我一遍学习一边写出来的,希望能够帮到大家,一起学习.效果如图所示: html代码如下所示: <html xmlns=" ...

  2. angular源码分析:angular的源代码目录结构说明

    一.读源码,是选择"编译合并后"的呢还是"编译前的"呢? 有朋友说,读angular源码,直接看编译后的,多好,不用管模块间的关系,从上往下读就好了.但是在我看 ...

  3. javascript 对象初探 (四)--- 内建对象之旅之Array

     我们不要去纠结神马是内建对象,神马是內建构造器.到后来你们便会发现其实她们都是对象. Array()是一个构建数组的內建构造器函数: var arr = new Array(); 与下面的是等效的: ...

  4. AE选中要素

    private void 选中要素ToolStripMenuItem_Click(object sender, EventArgs e) { if(axMapControl2.LayerCount&l ...

  5. [Java] Tomcat环境变量设置

    @echo off title Tomcat环境变量设置 color 0a set /p inputTH=D:\Work\024_Tomcat if /i "%inputTH%"= ...

  6. mysql 数据库服务中的应用程序

    mysql 是一个数据库服务,而实现数据库服务是由mysql中的很多子应用程序来完成的(http://dev.mysql.com/doc/refman/5.7/en/programs-overview ...

  7. JSONKit does not support Objective-C Automatic Reference Counting(ARC) / ARC forbids Objective-C objects in struct

    当我们在使用JSONKit处理数据时,直接将文件拉进项目往往会报这两个错“JSONKit   does not support Objective-C Automatic Reference Coun ...

  8. UI中一些不常用的控件UIActivityIndicatorView、UIProgressView、UISegmentedControl、UIStepper、UISwitch、UITextView、UIAlertController

    //UIActivityIndicatorView //小菊花,加载 #import "ActivityIndicatorVC.h" @interface ActivityIndi ...

  9. iOS 使用GCD实现倒计时效果

    在APP开发过程中,经常有需要实现倒计时效果, 比如语音验证码倒计时...代码如下: __block int timeout = 100; dispatch_queue_t queue = dispa ...

  10. redis数据类型

    Redis 数据类型 Redis支持五种数据类型:string(字符串),hash(哈希),list(列表),set(集合)及zset(sorted set:有序集合). String(字符串) st ...