赞
踩
下面是POSIX标准中关于程序名、参数的约定:
函数功能:对命令行的选项进行处理
函数返回值:如果命令行中输入的选项可以和optstring字符串中的字符选项匹配,那么返回选项字符,如果不在有可以识别的选项返回-1
函数原型:
int getopt(int argc, char *argv[], const char *optstring);
参数:
argc:主函数的参数
argv:主函数的参数
optstring:选项字母组成的字串,举例“ab:c::d”,做一下分析
getopt设置的全局变量:
getopt(int argc, char *argv[], "ab:c:de::")
/*调用过程分析
0 1 2 3 4 5 6 7 8 9
./test file1 -a -b -c code -d file2 -e file3
扫描过程中(扫描范围argv[1]到argv[argc-1]),optind是下一个选项的索引, 非选项参数将跳过,同时optind增1。optind初始值为1。当扫描argv[1]时,为非选项参数,跳过直接进行下一次扫描,optind=2;扫描到-a选项时和optstring中的选项字符可以匹配,返回字符a,然后做相关处理,下一个将要扫描的选项是-b,则optind更改为3;扫描到-b选项时,后面有参数(会认为-c为选项b的参数),optind=5,扫描到code非选项跳过optind=6;扫描到-d选项,后面没有参数,optind=7;扫描到file2非选项跳过optind=8;扫描到-e后面本来应该有参数,optind=9但是有空格所以e的参数为空
*/
/*
扫描结束后,将选项及参数依次放到argv数组的最左边,非选项参数依次放到argv的最后边
0 1 2 3 4 5 6 7 8 9
./test -a -b -c -d -e file1 code file2 file3
同时,optind会指向非选项的第一个参数,如上面,optind将指向file1
*/
注意:如果调用过程中发现没有选项参数的选项合并在一起,比如-a和-d写成-ad,那么这时候。optind不会加1,但是getopt还会正常扫描
实例程序:
/******************************************************** * Copyright (C) 2017 All rights reserved. * * Filename:getopt.c * Author :YHD * Date :2017-06-04 * Describe: * ********************************************************/ #include <stdbool.h> #include <errno.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <stdio.h> int main(int argc, char *argv[]) { int opt; opterr = 0; printf("optind = %d\n", optind); while ((opt = getopt(argc, argv, ":asd:")) != -1) { switch (opt) { case 'a': printf("I am a!\n"); break; case 's': printf("I am s!\n"); break; case 'd': printf("I am d!\n"); printf("input parameter is %s\n", optarg); break; case '?': printf("无效的字符 char is %c\n", optopt); break; case ':': printf("lack of the option parameter!\n"); break; } printf("argv[%d] = %s\n", optind, argv[optind]); } int i; for (i = 0; i < argc; i++) { printf("argv[%d] = %s\n", i, argv[i]); } printf("argv[%d] = %s\n", optind, argv[optind]); return 0; } //方式1 root@ubuntu:/mnt/hgfs/farsight/work/work_dada/test_dada/getopt# ./getopt -a -s -x -a asdasd -d optind = 1 I am a! argv[2] = -s I am s! argv[3] = -x 无效的字符 char is x argv[4] = -a I am a! argv[5] = asdasd lack of the option parameter! argv[7] = (null) argv[0] = ./getopt argv[1] = -a argv[2] = -s argv[3] = -x argv[4] = -a argv[5] = -d argv[6] = asdasd argv[6] = asdasd //方式2 root@ubuntu:/mnt/hgfs/farsight/work/work_dada/test_dada/getopt# ./getopt -as -x -a asdasd -d optind = 1 I am a! argv[1] = -as I am s! argv[2] = -x 无效的字符 char is x argv[3] = -a I am a! argv[4] = asdasd lack of the option parameter! argv[6] = (null) argv[0] = ./getopt argv[1] = -as argv[2] = -x argv[3] = -a argv[4] = -d argv[5] = asdasd argv[5] = asdasd
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。