Last active
February 9, 2016 22:29
-
-
Save 17twenty/8787d3cdd2fa85163a3b to your computer and use it in GitHub Desktop.
Decided that getopt sucked so rolled my own. Meets spec!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <time.h> | |
#include <string.h> | |
#define MAX_FLAG_LENGTH 20 | |
typedef int (*fn_pointer_t)(void *data); | |
// We flag -> callback structure. | |
struct optionFunc { | |
char optflag[MAX_FLAG_LENGTH]; | |
fn_pointer_t callback; | |
}; | |
int show_usage(void *data) { | |
printf("THIS IS show_usage!\n"); | |
return 0; | |
} | |
int request_status(void *data) { | |
printf("THIS IS request_status!\n"); | |
return 0; | |
} | |
int request_group(void *data) { | |
printf("THIS IS request_group!\n"); | |
return 0; | |
} | |
int join_group(void *data) { | |
if (data == NULL) { | |
printf("Please specify a callgroup\n"); | |
return -1; | |
} | |
int group = strtol((char *)data, NULL, 10); | |
printf("THIS IS join_group %d!\n", group); | |
return 0; | |
} | |
int get_token(void *data) { | |
printf("THIS IS get_token!\n"); | |
return 0; | |
} | |
int release_token(void *data) { | |
printf("THIS IS release_token!\n"); | |
return 0; | |
} | |
int reload_config(void *data) { | |
printf("THIS IS reload_config!\n"); | |
return 0; | |
} | |
int save_config(void *data) { | |
printf("THIS IS save_config!\n"); | |
return 0; | |
} | |
struct optionFunc g_option_table[] = { | |
{ "--help", show_usage }, | |
{ "--get-status", request_status }, | |
{ "--get-group", request_group }, | |
{ "--join", join_callgroup }, | |
{ "--get-token", get_token }, | |
{ "--release-token", release_token }, | |
{ "--save-config", reload_config }, | |
{ "--load-config", save_config }, | |
}; | |
#define NELEMS(x) (sizeof(x) / sizeof((x)[0])) | |
#define MAX_OPTIONS NELEMS(g_option_table) | |
int main(int argc, char **argv) | |
{ | |
int option = 0; // Defaults to usage | |
void *data = NULL; | |
// Handle command line arguments | |
for (int i = 1; i < argc; ++i) { | |
for (int j = 0; j < MAX_OPTIONS; ++j) { | |
if (strcmp(argv[i], g_option_table[j].optflag) == 0) { | |
// We found our option - if there's an operand, grab it as a parameter for option | |
option = j; | |
if (i < argc) { | |
data = argv[i + 1]; | |
} | |
break; | |
} | |
} | |
} | |
return g_option_table[option].callback(data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Added a char help_message[MAX_HELP_LENGTH] to the struct and used it in the usage function i.e.: