#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"); } /* not all argv are options, an element of argv that starts with '-' is an option //If getopt() is called repeatedly, it returns successively each of //the option characters from each of the option elements. #include <unistd.h> int getopt(int argc, char * const argv[], const char *optstring); extern char *optarg; //pointer the parameter of an option extern int optind; //indicate the position of argv to help the next call getopt() which can resume the scan extern int opterr; //if opterr is set to 0 (i.e., opterr = 0;), the calling program will prevent the error message extern int optopt; //If getopt() does not recognize an option character, it prints an error message to stderr, stores the character in optopt, and returns ’?’. */ void get_opt_in_short(int argc, char **argv){ //If a character is followed by a colon, the option requires an argument //Two colons mean an option takes an optional arg const char *short_options = "N:n:i::h"; int opt; opterr = 0; while((opt = getopt(argc, argv, short_options)) != -1){ switch(opt){ case 'N': printf("Node -N, optarg = %s\n", optarg); break; case 'n': printf("Task -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); } //If there are no more option characters, getopt() returns -1. //Then optind is the index in argv of the first argv-element that is not an option. printf("after scan, optind = %d\n", optind); } int main(int argc, char **argv){ get_opt_in_short(argc, argv); return 0; }