getopt_long


#include <stdio.h> //for printf
#include <stdlib.h> //for exit
#include <unistd.h>
#include <getopt.h>

void print_help(){
    puts("srun [-N nodes] [-n tasks] executable\n\
    		-N      number of nodes\n\
            -n      number of tasks\n\
            -h --help   print the help");  
}

/*
 * no_argument (or 0) if  the  option  does not take an argument;
 * required_argument (or 1) if the option requires an argument;
 * optional_argument (or 2) if the option takes an optional argument.
 *
 * struct option {
	  const char *name;
	  int has_arg;
	  int *flag;
	  int val;  //is the value to return, or to load into the variable pointed to by flag.
   };
   The last element of the array has to be filled with zeroes.
 */
struct option long_options[] = {
    { "nodes", 			1, 	NULL,	'N' },
    { "tasks",  		1, 	NULL,  	'n' },
    { "interaction",	2, 	NULL,  	'i' },
    { "help",     		0, 	NULL,  	'h' },
    { 0, 				0, 	0, 	 	0	}
};  //const char *short_options = "N:n:i::h";
/*
#define _GNU_SOURCE
#include <getopt.h>

int getopt_long(int argc, char * const argv[], const char *optstring,
			const struct option *longopts, int *longindex);
//longopts is a pointer to the first element of an array of struct option

int getopt_long_only(int argc, char * const argv[], const char *optstring,
		  	  const struct option *longopts, int *longindex);
//If longindex is not NULL, it points to a variable which is set to
//the index of the long option relative to longopts.
 */
void get_opt_in_long(int argc, char **argv){
	const char *short_options = "N:n:i::h";
	int opt;
	while((opt = getopt_long(argc, argv, short_options, long_options, NULL)) != -1){
		switch(opt){
		case 'N':
			printf("nodes -N, optarg = %s\n",  optarg);
			break;
		case 'n':
			printf("tasks -n, optarg = %s\n", optarg);
			break;
		case 'i':
			if(!optarg)
				puts("Nict to meet you!");
			else
				printf("Nict to meet you! %s\n", optarg);
			break;
		case 'h':
			print_help();
			break;
		case '?':
			printf("can't recognize, the optopt = %c\n", (char)optopt);
			break;
		default:
			break;
		}
		printf("optind = %d\n", optind);
	}
	//after scan options, other argv has been moved to the end part of argv[]
	if(optind < argc){
		for(; optind < argc; optind++)
			printf("%s ", argv[optind]);
		putchar('\n');
	}
}

int main(int argc, char **argv){
	get_opt_in_long(argc, argv);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值