HI All, . , : --file'thing ' split, .
, char , . , main.cpp .
, quotegrouping : and = ' " / args, -flag: 1 -file" c:\test ". . , :
optparse opt(argstring);
g_someint = strtoul(opt.get('--debuglevel','0'),0,0);
g_somebool = opt.get('--flag')!=0;
g_somestring = opt.get('--file','default.txt')
: , , . .
#include <string.h>
#include <stdio.h>
struct optparse{
optparse(const char *args, size_t len = 0) : first(0) {
size_t i;
if(!args)args = "";
if(!len)for(;args[len];len++);
for(buf=new char[len+1],i=0;i<len;i++)buf[i]=args[i];buf[i]=0;
opt *last = first;
char *c = buf, *b = c, *v = 0, g = 0, e = 0;
do{
if(*c=='\\') e = e?0:1;
else if(e?--e:1){
if(g){ if(*c == g) g = 0; }
else {
if(*c=='"' || *c=='\''){ if(b<c && !v) v = c; g = *c; }
else if(!v && (*c==':' || *c=='=')) v = c;
else if(*c==' '){
if(b<c)last = new opt(last,&first,b,c,v);
b = c+1, v = 0;
}
}
}
if(*c) c++;
if(!*c && b<c) last = new opt(last,&first,b,c,v);
}while(*c);
for(opt *i = first; i; i = i->next) *(i->ne) = 0, *(i->ve) = 0;
}
~optparse(){
delete buf;
while(first){
opt *t = first->next;
delete first;
first = t ;
}
}
const char *get( const char *name, const char *def= 0){
size_t l = strlen(name);
for(opt *i = first;i;i = i->next) if( _strnicmp( i->name, name, l ) == 0)
return i->value;
return def;
}
struct opt{
opt( opt *last, opt **first, char *s, char *e, char *v){
if(!*first) *first = this; if(last) last->next = this;
if(v && (*v=='\'' || *v=='"') && (*(e-1)=='\'' || *(e-1) == '"'))e--;
next = 0, name = s, value = v?v+1:"", ne = v?v:e, ve = e;
}
char *name, *value, *ne, *ve;
opt *next;
};
char *buf;
opt *first;
};
int main(){
const char *v, *test ="--debug:1 -file'c:\\something' --odd=10";
optparse opts(test);
if(v = opts.get("--debug")){
printf("debug flag value is %s\n",v);
}
for(optparse::opt *i=opts.first;i;i=i->next){
printf("name: %s value: %s\n",i->name,i->value);
}
}
.
,
if(b<c)last = new opt(last,&first,b,c,v);
b = c+1, v = 0;
if(*b=='-' && *(c+1)!='-')v = v?v:c;
else{
if(b<c)last = new opt(last,&first,b,c,v);
b = c+1, v = 0;
}
"": -debug 1
--files a.txt b.txt c.txt
, : ( Windows) == ':'