Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "tsm_getopt.h"
// Structure to keep all global variables in one place.
struct {
float fval;
const char *stringval;
const char *mandatorystring;
int ival;
int optionalflag;
float mandatoryfloat;
} globals={
3.14159, // Default value for fval
"where in the world", // Default value for stringval
NULL, // Mandatory, NULL if not set for error
0, // Default value for ival
0, // default value for optionalflag
0.0/0.0, // mandatory, defaults to invalid 0/0 if not set
};
const opt options[]={
// "fval" for "--fval" argument,
// 'f' for '-f' argument,
// 1 since it takes one argument,
// a pointer to a float number,
// "%f" to read one float,
// and "Float Value" to print as help text.
{"fval", 'f', 1, &globals.fval, "%f", "Float value"},
// Similar, but an integer number.
{"ival", 'i', 1, &globals.ival, "%d", "Integer value"},
// A string. Needs a pointer to a char *(not the char * itself).
{"sval", 's', 1, &globals.stringval, NULL, "String Value"},
{"mstr", 'm', 1, &globals.mandatorystring, NULL, "Mandatory string"},
// An option with no parameters.
// Changes globals.optionalflag from 0 to 1 if set.
{"optionalflag", 'o', 0, &globals.optionalflag, NULL, "optional flag"},
// Need this as the last thing in the list, to tell when the list ends
{"mfloat", 'l', 1, &globals.mandatoryfloat, "%f", "Mandatory float"},
{NULL},
};
int main(int argc, char *argv[])
{
if(argc < 2) // No arguments
{
tsm_usage(argc, argv, options);
exit(1);
}
if(tsm_getopt(argc, argv, options) < 0)
{
tsm_usage(argc, argv, options);
exit(1);
}
// Check any mandatory arguments
if(globals.mandatorystring == NULL)
{
printf("mandatorystring not set\n");
exit(1);
}
if(globals.ival == 0)
{
printf("ival not set\n");
exit(1);
}
if(isnan(globals.mandatoryfloat))
{
printf("mfloat not set\n");
exit(1);
}
// Arguments should now be ready.
printf("fval = %f\n", globals.fval);
printf("stringval = %s\n", globals.stringval);
printf("mandatorystring = %s\n", globals.mandatorystring);
printf("ival = %d\n", globals.ival);
printf("optionalflag = %d\n", globals.optionalflag);
printf("mandatoryfloat = %f\n", globals.mandatoryfloat);
return(0);
}