I'm making a project that needs a simple cross-platform command-line parser. I made this. Hope you enjoy!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#define __NUM_OF_ELEMENTS(ARR) (sizeof(ARR)/sizeof(ARR[0]))
#define __HAS_ARG(FLAGS, ARG) (FLAGS & (1 << ARG))
void panic(const char *fmt, ...){
fprintf(stderr, "error: ");
va_list arglist;
va_start( arglist, fmt );
vfprintf(stderr, fmt, arglist);
va_end( arglist );
exit(EXIT_FAILURE);
}
void help(const char * progName){
char * whoami = 0;
(whoami = strrchr(progName, '/')) ? ++whoami : (whoami = progName);
printf(
"%s is intended to do blah\n"
"Options:\n"
" --help Display This message\n"
" --file [file name] Input file to use\n",
whoami);
exit(EXIT_SUCCESS);
}
int main(int argc, char *argv[])
{
if(argc == 1){
help(argv[0]);
}
const char * args[] = {"--help", "--file", "--2cool4scool"};
enum {HELP_ARG, FILE_ARG, TOO_COOL_FOR_SCHOOL_ARG};
unsigned int flags = 0;
//skip prog name
for(unsigned int arg = 1, i = 0; arg < argc; ++arg){
for(i = 0; i < (unsigned int)__NUM_OF_ELEMENTS(args); ++i){
if(!strcmp(argv[arg], args[i])){
flags |= 1 << i;
goto CMD_ARGUMENT_FOUND;
}
}
//argument is not found / unkown arg
panic("Argument '%s' not found\n", argv[arg]);
CMD_ARGUMENT_FOUND:;
}
if(__HAS_ARG(flags, HELP_ARG)){
help(argv[0]);
}
if(__HAS_ARG(flags, TOO_COOL_FOR_SCHOOL_ARG)){
puts("Hell YA!");
}
return 0;
}