Today I came across a function [getopt] by accident.
It is very useful to parse command-line arguments with this tool!
Here is:
#inlcude <unistd.h>
int getopt(int argc, char * const argv[], const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
#include <getopt.h>
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);
Explain for getopt():
- Arguments argc and argv are the argument count and array as passed to the main() function.
- optstring is the options set. One semicolon following a character means that character need a argument, and two semicolon mean the argument is optional.
- optind is the index of the next element to be processed in argv. The system initializes this value to 1. You can reset it to 1 to restart scanning of the same argv, or when scanning a new argument vector.
- If there are no more option characters, getopt() returns -1 or, it will keep return the ASCII of the current character.
- optarg points to the argument string of one option if that option has argument following.
E.g.
#include <unistd.h>
#include <stdio.h>
#include <stdbool.h> // bool type
/* Macro Definition */
#define NO 0
#define YES 1
#define OK 0
#define ERROR -1
/* Structure for Global Arguments */
struct GlbArgs_t{
bool version;
bool help;
char *number;
char *type;
}GlbArgs;
/* Options allowed */
static const char *optString = "n:t::vh?";
/* Usage */
static const char *usage = "Usage: \n"
"-n\n"
"-tx (x=type-name) \n"
"-v\n"
"-h -?\n";
/* Initialize Global Argument structure */
void InitGlbArg()
{
GlbArgs.version = NO;
GlbArgs.help = NO;
GlbArgs.number = NULL;
GlbArgs.type = NULL;
}
int main(int argc, char **argv)
{
int opt = 0; // option
InitGlbArg();
while((opt = getopt(argc, argv, optString)) != ERROR){
switch(opt){
case 'n':
GlbArgs.number = optarg;
printf("Number: %s\n", GlbArgs.number);
break;
case 't':
GlbArgs.type = optarg;
printf("Type: %s\n", GlbArgs.type);
break;
case 'v':
GlbArgs.version = YES;
printf("Version: 1.0\n");
break;
case 'h':
case '?':
printf("%s", usage);
break;
default:
break;
}
}
return OK;
}
- Learn a lot from here
- For more details, refer to [man 3 getopt] (LInux)