1. 程式人生 > >C/C++解析命令行參數

C/C++解析命令行參數

linux c/c++

相關庫函數
#include <unistd.h>
#include <getopt.h>

int getopt(int argc, char * const argv[],const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;


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);


eg1:

#include <stdio.h>
#include <getopt.h>

int main(int argc,char *argv[]) {

    int opt;
    char *optstring = "a:b:c:de"; // 分別代表-a,-b,-c,-d,-e命令行參數,其中帶:的表示參數可以指定值,故de不能指定值

    while((opt = getopt(argc,argv,optstring)) != -1){
        printf("opt = %c\n",opt);
        printf("optarg = %s\n",optarg);
        printf("optind = %d\n",optind);
        printf("argv[optind-1] = %s\n\n",argv[optind-1]);

    }


    return 0;
}

#./test_arg -a 1 -b 2 -c 3 -d -e
opt = a
optarg = 1
optind = 3
argv[optind-1] = 1

opt = b
optarg = 2
optind = 5
argv[optind-1] = 2

opt = c
optarg = 3
optind = 7
argv[optind-1] = 3

opt = d
optarg = (null)
optind = 8
argv[optind-1] = -d

opt = e
optarg = (null)
optind = 9
argv[optind-1] = -e


本文出自 “程序員發展之路” 博客,請務必保留此出處http://xwandrew.blog.51cto.com/2909336/1971684

C/C++解析命令行參數