diff --git a/include/MDE/CommandLine.h b/include/MDE/CommandLine.h index 1185d2a..de95e8a 100644 --- a/include/MDE/CommandLine.h +++ b/include/MDE/CommandLine.h @@ -1,10 +1,23 @@ #ifndef __MDE_COMMANDLINE_H__ #define __MDE_COMMANDLINE_H__ +#include + #ifdef __cplusplus extern "C" { #endif +typedef struct _MDECommandLine MDECommandLine; + +struct _MDECommandLine { + const char* short_opt; + const char* long_opt; + int need_arg; + void(*call)(const char* arg); +}; + +int MDECommandLineParse(MDECommandLine* param, int count, int argc, char** argv); + #ifdef __cplusplus } #endif diff --git a/src/commandline.c b/src/commandline.c index 3bb3305..ed6c880 100644 --- a/src/commandline.c +++ b/src/commandline.c @@ -1 +1,39 @@ #include + +int MDECommandLineParse(MDECommandLine* param, int count, int argc, char** argv){ + int i; + for(i = 1; i < argc; i++){ + int j; + for(j = 0; j < count; j++){ + char* s = malloc(1 + strlen(param[j].short_opt) + 1); + char* l = malloc(2 + strlen(param[j].long_opt) + 1); + + strcpy(s, "-"); + strcat(s, param[j].short_opt); + + strcpy(l, "--"); + strcat(s, param[j].long_opt); + + if(strcmp(s, argv[i]) == 0 || strcmp(l, argv[i]) == 0){ + free(l); + free(s); + + if(param[j].need_arg && (i + 1) >= argc){ + fprintf(stderr, "%s: %s needs 1 argument\n", argv[0], argv[i]); + return 1; + }else if(param[j].need_arg){ + param[j].call(argv[++i]); + }else{ + param[j].call(NULL); + } + + break; + }else{ + free(l); + free(s); + } + } + } + + return 0; +}