getopt_long为解析命令行参数函数,它是Linux C库函数。使用此函数需要包含系统头文件getopt.h。

getopt_long函数声明如下:

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

getopt_long的工作方式与getopt类似,关于getopt的介绍可以参考: https://blog.csdn.net/fengbingchun/article/details/81122843   。但是getopt_long除了接受短选项外还接受长选项,长选项以"--"开头。如果程序只接受长选项,那么optstring应指定为空字符串。如果缩写是唯一的,那么长选项名称可以缩写。长选项可以采用两种形式:--arg=param或--arg param. longopts是一个指针指向结构体option数组。

结构体option声明如下:

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

name:长选项的名字

has_arg:0,不需要参数;1,需要参数;2,参数是可选的

flag:指定如何为长选项返回结果。如果flag是null,那么getopt_long返回val(可以将val设置为等效的短选项字符),否则getopt_long返回0.

val:要返回的值。

结构体option数组的最后一个元素必须用零填充

当一个短选项字符被识别时,getopt_long也返回选项字符。对于长选项,如果flag是NULL,则返回val,否则返回0。返回-1和错误处理方式与getopt相同。

下面是从其他文章中copy的测试代码,详细内容介绍可以参考对应的reference:

CMakeLists.txt文件内容如下:

PROJECT(samples_cplusplus)
CMAKE_MINIMUM_REQUIRED(VERSION 3.0)# 支持C++11
SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -Wall -O2 -std=c11")
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}  -g -Wall -O2 -std=c++11")INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR})FILE(GLOB samples ${PROJECT_SOURCE_DIR}/*.cpp)FOREACH (sample ${samples})STRING(REGEX MATCH "[^/]+$" sample_file ${sample})STRING(REPLACE ".cpp" "" sample_basename ${sample_file})ADD_EXECUTABLE(test_${sample_basename} ${sample})TARGET_LINK_LIBRARIES(test_${sample_basename} pthread)
ENDFOREACH()

sample_getopt_long.cpp内容如下:

#include <iostream>
#include <getopt.h>
#include <string.h>int main(int argc, char* argv[])
{// reference: http://man7.org/linux/man-pages/man3/getopt.3.htmlint c;int digit_optind = 0;while (1) {int this_option_optind = optind ? optind : 1;int option_index = 0;static struct option long_options[] = {{"add",       required_argument,  0,  0},{"append", no_argument,        0,  0},{"delete", required_argument,  0,  0},{"verbose",    no_argument,        0,  0},{"create", required_argument,  0,  'c'},{"file",   required_argument,  0,  0},{0,      0,          0,  0}};c = getopt_long(argc, argv, "abc:d:012", long_options, &option_index);if (c == -1) break;switch (c) {case 0://fprintf(stdout, "option %s ", long_options[option_index].name);//if (optarg) fprintf(stdout, "with arg %s", optarg);//fprintf(stdout, "\n");if (strcmp(long_options[option_index].name, "add") == 0)fprintf(stdout, "long option \"add\" value: %s\n", optarg);else if (strcmp(long_options[option_index].name, "append") == 0)fprintf(stdout, "long option \"append\"\n");else if (strcmp(long_options[option_index].name, "delete") == 0)fprintf(stdout, "long option \"delete\" value: %s\n", optarg);else if (strcmp(long_options[option_index].name, "create") == 0)fprintf(stdout, "long option \"create\" value: %s\n", optarg);else if (strcmp(long_options[option_index].name, "verbose") == 0)fprintf(stdout, "long option \"verbose\"\n");else if (strcmp(long_options[option_index].name, "file") == 0)fprintf(stdout, "long option \"file\" value: %s\n", optarg);break;case '0':case '1':case '2':if (digit_optind != 0 && digit_optind != this_option_optind)fprintf(stdout, "digits occur in two different argv elements.\n");digit_optind = this_option_optind;fprintf(stdout, "option %c\n", c);break;case 'a':fprintf(stdout, "option a\n");break;case 'b':fprintf(stdout, "option b\n");break;case 'c':fprintf(stdout, "option c with value '%s'\n", optarg);break;case 'd':fprintf(stdout, "option d with value '%s'\n", optarg);break;case '?':break;default:fprintf(stdout, "?? getopt returned character code 0%o ??\n", c);} }if (optind < argc) {fprintf(stdout, "non-option argv elements: ");while (optind < argc)fprintf(stdout, "%s ", argv[optind++]);fprintf(stdout, "\n");}exit(EXIT_SUCCESS);
}

bash.sh内容如下:

#! /bin/bashreal_path=$(realpath $0)
dir_name=`dirname "${real_path}"`
echo "real_path: ${real_path}, dir_name: ${dir_name}"new_dir_name=${dir_name}/build
mkdir -p ${new_dir_name}
cd ${new_dir_name}
cmake ..
makecd -

run_getopt_long.sh内容如下:

#! /bin/bashreal_path=$(realpath $0)
dir_name=`dirname "${real_path}"`
echo "real_path: ${real_path}, dir_name: ${dir_name}"echo -e "\n\ntest argv1:"; ${dir_name}/build/test_sample_getopt_long
echo -e "\n\ntest argv2:"; ${dir_name}/build/test_sample_getopt_long -?
echo -e "\n\ntest argv3:"; ${dir_name}/build/test_sample_getopt_long --add xxx
echo -e "\n\ntest argv4:"; ${dir_name}/build/test_sample_getopt_long -a xx -b yy -c zz -d rr -0 ss -1 tt -2 qq
echo -e "\n\ntest argv5:"; ${dir_name}/build/test_sample_getopt_long --add Tom --append Jim --delete Rucy --verbose XXX --create new_data --file a.txt -ab -c 111 -d 222
echo -e "\n\ntest argv6:"; ${dir_name}/build/test_sample_getopt_long -xxx yyy
echo -e "\n\ntest argv7:"; ${dir_name}/build/test_sample_getopt_long -a

执行过程:首先执行build.sh,然后再执行run_getopt_long.sh即可。

GitHub: https://github.com/fengbingchun/Linux_Code_Test

Linux下getopt_long函数的使用相关推荐

  1. linux下syscall函数,SYS_gettid,SYS_tgkill

    出处:http://blog.chinaunix.net/uid-28458801-id-4630215.html linux下syscall函数,SYS_gettid,SYS_tgkill 2014 ...

  2. linux下system函数的深入理解

    这几天调程序(嵌入式linux),发现程序有时就莫名其妙的死掉,每次都定位在程序中不同的system()函数,直接在shell下输入system()函数中调用的命令也都一切正常.就没理这个bug,以为 ...

  3. Linux下curses函数库的详细介绍

    Linux下curses函数库的详细介绍 curses库介绍 安装 curses库函数介绍 初始化和重置函数 管理屏幕的函数 输出到屏幕 从屏幕读取 清除屏幕 移动光标 字符属性 管理键盘的函数 键盘 ...

  4. linux下readlink函数详解

    linux下readlink函数详解 相关函数: stat, lstat, symlink 表头文件: #include <unistd.h> 定义函数:int  readlink(con ...

  5. linux 纪元时间转换,[转]Linux下时间函数time gettimeofday

    Linux下时间函数time & gettimeofday UNIX及Linux的时间系统是由「新纪元时间」Epoch开始计算起,单位为秒.Epoch是指定为1970年1月1日凌晨零点零分零秒 ...

  6. Linux下connect函数 阻塞 与 非阻塞 问题

    一.概述 linux系统下,connect函数是阻塞的,阻塞时间的长度与系统相关.而如果把套接字设置成非阻塞,调用connect函数时会报错Operation now in progress,且err ...

  7. Linux下select函数实现的聊天服务器

    转载: http://blog.csdn.net/microtong/article/details/4989902 Linux下select函数实现的聊天服务器  佟强 http://blog.cs ...

  8. LINUX下poll函数用法

    LINUX下poll函数用法 文章目录 LINUX下poll函数用法 一.函数介绍 二.使用 1. 一.函数介绍 int poll(struct pollfd *fds, nfds_t nfds, i ...

  9. linux 函数返回string,linux 下c函数strcmp的返回值疑问?

    linux 下c函数strcmp的返回值疑问? strcmp函数解释: NAME strcmp, strncmp - compare two strings SYNOPSIS #include int ...

最新文章

  1. 找出数组中出现次数最多的一项并统计次数
  2. MySQL replace into 的坑以及insert相关操作
  3. mysql 触发器定义变量_MySQL 函数存储过程触发器定义简单示例
  4. POJ 1523 SPF (割点 点双连通分量)
  5. EBS AP 创建会计科目失败
  6. JetBrains注册码计算(IntelliJ IDEA 15.0注册码激活)
  7. html5+JS调用手机摄像头扫码
  8. 蓝牙模块HC-06的基本设置和他的AT指令集
  9. 《计算机组网试验-DNS域名服务协议 》杭州电子科技大学
  10. mysql 获取百分比函数,并对结果保留2位小数。
  11. android八方向手势,Android开发中顺时针逆时针滑动手势的识别算法
  12. SparkSQL和HiveSql的对比
  13. Spring Cloud与Dubbo优缺点详解
  14. flutter引入高德地图_Flutter接入高德地图后运行报错
  15. 计算机连接打印机用户数量修改,win7系统下局域网如何限制每台打印机的使用成员数量...
  16. 人人憎恨的大数据杀熟你了解吗? 大数据杀熟”是否真的存在?
  17. 国外大牛的黑苹果配置清单
  18. javaWeb10(ckeditorsmartupload)
  19. 基于perl的bleu得分和nist得分计算实现
  20. 有哪些小巧舒适的蓝牙耳机?推荐几款小巧且舒适的蓝牙耳机

热门文章

  1. 在Python上使用OpenCV检测和跟踪行人
  2. 什么是self-attention、Multi-Head Attention、Transformer
  3. 设置VSCode快捷键vue生成代码片段
  4. 在Ubuntu 16.04.6 LTS上安装python3.7和pip3后出现Command '('lsb_release', '-a')' 出错问题的解决方法
  5. 在CentOS 6.9 x86_64的nginx 1.12.2上开启ngx_http_geo_module模块实录
  6. 在Ubuntu 14.04 64上安装gevent_zeromq-0.2.5
  7. Blender3.0动画制作入门学习教程 Learn Animation with Blender (2021)
  8. LTE-连接态下的DRX
  9. C++ 技能树(持续更新)
  10. C# Task注意事项