Created
May 20, 2016 01:26
-
-
Save dvtate/e5a1380e7901687b07b3b973eb70af79 to your computer and use it in GitHub Desktop.
a simple [incomplete] command-line parsing library...
This file contains hidden or 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
#ifndef ARG_PARSE_H | |
#define ARG_PARSE_H | |
#include <string.h> // strcmp, strcat | |
#include <stdlib.h> // atoi | |
char* findOccurance(char*,char*); | |
void getArgs(int, char**, char*, ...); | |
char hasArg(int,char**, char*); | |
char* strAfter(int, char**, char*); | |
char* findOccurance(char* source, char* query){ | |
char* queryCopy = query; | |
while ( *source != '\0') { | |
if (*(source++) == *query) { | |
query++; | |
while (*query != '\0' && *source == *query) { | |
source++; | |
query++; | |
} | |
if (*query == '\0') | |
return source; | |
query = queryCopy; | |
} | |
} | |
return NULL; // return NULL if there were no occurances found... | |
} | |
char hasArg(int argc, char** args, char* arg){ | |
// return 1 when an argument matches arg | |
for (;argc > 0; argc--) | |
if (strcmp(arg, *args++) == 0) | |
return 1; | |
// no matches found | |
return 0; | |
} | |
// # = int | |
// & = double | |
// * = string | |
// no-suffix = boolean | |
// returns -1 if the programmer fucked up the scheme string | |
// returns 1 if the arguments | |
char getArgs(int argc, char** args, char* scheme, ...){ | |
va_list argsList; | |
va_start(argsList, scheme); | |
while (*scheme != '\0'){ | |
// ignore spaces... | |
if (*scheme ==' ') { | |
scheme++; | |
continue; | |
} | |
// skip commas | |
if (*scheme == ',') { | |
scheme++; | |
continue; | |
} | |
char opt = *scheme++; | |
// ignore spaces... | |
// while (*scheme == ' ') | |
// scheme++; | |
if (*scheme == ',') { // boolean | |
// c doesn't have bools :P | |
char* ans = va_arg(argsList, char*); | |
char option[3] = "-"; | |
strcat(option, opt); | |
*ans = hasArg(argc, args, option); | |
} else if (*scheme == '*') { // string | |
char** ans = va_arg(argsList, char**); | |
*ans = strAfter(argc, args, opt); | |
} else if (*scheme == '#') { // integer | |
} else if (*scheme == '&' | |
} else { return -1 } | |
} | |
va_end(argsList); | |
return 0; | |
} | |
inline char* strAfter(int argc, char** args, char search){ | |
for (;argc > 0; argc--) { | |
if (**args == '-') | |
(*args)++; | |
if (**args == search) | |
return ++(*args); | |
args++; | |
} | |
return NULL; | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment