Skip to content
Find file
Fetching contributors…
Cannot retrieve contributors at this time
204 lines (166 sloc) 2.94 KB
#ifndef com_sleepless_args_cpp
#define com_sleepless_args_cpp
/* Copyright 1998-2011 Sleepless Software Inc. All Rights Reserved */
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include "array.cpp"
#include "str.cpp"
#ifdef WIN32
# define strdup _strdup
#endif
struct Args
{
char *buf;
int len;
Array shelf;
// This constructor breaks args down into white-space separated items.
// An item can contain spaces if it is enclosed in quotes.
// You can also enclose an item in apostrophe chars if you want an item
// that contains double quote chars.
// A few backslash-escaped cars are recognized:
// \\ (backslash)
// \t
// \n
// \r
Args(const char *input)
{
len = 0;
buf = strdup(input);
if(buf)
{
Str::trim(buf);
int sep = ' ';
char *cp = buf;
while(*cp)
{
// skip whitespace
while(*cp && isspace(*cp))
cp++;
if((*cp == '"') || (*cp == '\''))
{
sep = *cp;
cp++;
}
shelf.put(len++, cp);
while(*cp && (*cp != sep))
{
if(*cp == '\\')
{
// escaped char
strcpy(cp, cp + 1);
if(*cp == 'n')
*cp = '\n';
else
if(*cp == 't')
*cp = '\t';
else
if(*cp == 'r')
*cp = '\r';
else
if(*cp == '\\')
*cp = '\\';
else
if(*cp == '"')
*cp = '"';
else
if(*cp == '\'')
*cp = '\'';
}
cp++;
}
if(*cp == sep)
{
*cp = 0;
cp++;
sep = ' ';
}
}
}
}
// This constructor does NOT handle quoted items. It works more simply
// by just breaking the string apart using 'sep' as the separator char.
Args(const char *input, int sep)
{
len = 0;
buf = strdup(input);
if(buf)
{
char *cp = buf;
shelf.put(len++, cp);
while((cp = strchr(cp, sep)))
{
*cp = 0;
cp++;
shelf.put(len++, cp);
}
}
for(int i = 0; i < len; i++)
Str::trim((char *)shelf.get(i));
}
~Args()
{
if(buf)
free(buf);
}
const char *get(int n)
{
if(buf && (n >= 0) && (n < len))
return (const char *)shelf.get(n);
return 0;
}
// Same as get, but always returns a valid pointer.
// If the arg indexed by 'n' doesn't exist, it returns ""
const char *aget(int n)
{
const char *s = get(n);
if(!s)
s = "";
return s;
}
int getInt(int n)
{
int r = 0;
const char *s = get(n);
if(s)
r = atoi(s);
return r;
}
unsigned long getULong(int n)
{
unsigned long r = 0;
const char *s = get(n);
if(s)
r = atol(s);
return r;
}
double getFloat(int n)
{
double r = 0;
const char *s = get(n);
if(s)
r = atof(s);
return r;
}
int length()
{
return len;
}
};
#ifdef MAIN
int main(int argc, char **argv)
{
for(int i = 1; i < argc; i++)
{
printf("Argument %d '%s':\n", i, argv[i]);
Args args(argv[i]);
for(int j = 0; j < args.len; j++)
{
printf(" arg[%d] = '%s'\n", j, args.get(j));
}
}
getchar();
return 0;
}
#endif
#endif // com_sleepless_args_cpp
Something went wrong with that request. Please try again.