Linux getopt_long函数调用
来源:互联网 发布:docker mysql 连接 编辑:程序博客网 时间:2024/06/06 18:00
许多Linux应用程序也接受比单字符选项含义更明确的参数。GNU C函数库包括getopt的另一个版本,称为getopt_long(),它接受以双划线(--)开始的长参数。
与getopt()函数相比,getopt多了两个参数。
一、函数原型
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex);
1、longopts:指向一个option结构体类型的数组,这个数组的每个元素指明了一个“长参数”的名称和性质等。
struct option {
const char *name;
int has_arg;
int *flag;
int val;
};
a、name:参数的名称
b、has_arg:是否带参数值,其数值可选。其中no_argument (即 0) 表明这个长参数不带参数(即不带数值,如:--name);required_argument (即 1) 表明这个长参数必须带参数(即必须带数值,如:--name Bob);optional_argument(即2)表明这个长参数后面带的参数是可选的,(即--name和--name Bob均可)。
c、flag:当这个指针为空的时候,函数直接将val的数值从getopt_long的返回值返回出去,当它非空时,val的值会被赋到flag指向的整型数中,而函数返回值为0。
d、val:用于指定函数找到该选项时的返回值,或者当flag非空时指定flag指向的数据的值。
2、longindex:如果longindex非空,它指向的变量将记录当前参数对应longopts数组中的第几个元素,即是longopts的下标值。
name 是参数的名称二、范例
#include <stdio.h>#include <unistd.h>#include <stdlib.h>#define _GNU_SOURCE#include <getopt.h>int main(int argc, char *argv[]){ int opt; struct option longopts[] = { { "initialize", 0, NULL, 'i'}, {”file", 1, NULL, 'f'}, {"list", 0, NULL, 'l'}, {'restart', 0, NULL, 'r'}, {0,0,0,0} }; while((opt = getopt_long(argc, argv, ":if:lr", longopts, NULL) ) != -1 ) { switch(opt){ case 'i': case 'l': case 'r': printf("option: %c\n", opt); break; case 'f': printf("filename: %s\n", optarg); break; case ':': printf("option needs a value\n"); break; case '?': printf("unknown option: %c\n",optopt); break; } for(;optind < argc; optind++) printf("argument: %s\n",argv[optind]); exit(0);}
注:长选项数组必须以一个包含全0的结构结尾。
- Linux getopt_long函数调用
- linux之getopt_long函数
- linux之getopt_long函数
- getopt_long函数基本用法-linux
- linux之getopt_long函数解析
- Linux getopt和getopt_long函数
- Linux getopt()函数 getopt_long()函数---转
- Linux下命令行程序设计--getopt_long()函数使用说明
- Linux选项解释-getopt和getopt_long函数
- Linux选项解释-getopt和getopt_long函数
- Linux编程里getopt_long函数用法详解
- linux选项解释-getopt和getopt_long函数
- linux中函数getopt_long用法解释
- getopt_long函数
- getopt_long函数
- getopt 函数 getopt_long函数
- getopt_long()函数的作用
- getopt_long函数学习笔记
- static
- [LeetCode] Binary Tree Preorder Traversal
- 小强的HTML5移动开发之路(44)——JqueryMobile中的按钮
- iOS应用直接调跳转到评价页面和应用下载页面
- 12306 并不是我们想的那样
- Linux getopt_long函数调用
- 为什么模板类不能支持分离编译
- 程序员面试题精选100题-不用+、-、×、÷做加法[算法]
- yii framework(一)入口分析
- 无法用语言来表达
- c#学习笔记(1)
- Eclipse 字体推荐
- 计算机网络安全检查
- C++primer plus第六版课后编程题答案7.5