Here's a simple C procedure which does that. I suppose you could build a simple wrapper around it to make it usefull in a shell. It's only the encode function but the decode shouldn't be to hard if you just reverse the process.
static char* urlencode(const char *instr)
{
register int ipos, bpos; // input str pos., buffer pos.
static unsigned char *str = NULL;
int len = strlen(instr);
int tmp;
//attempt to reuse buffer
if (str == NULL)
str = (unsigned char *) malloc(3 * len + 1);
else
str = (unsigned char *) realloc(str, 3 * len + 1);
//malloc, realloc failed ?
if (errno == ENOMEM)
{
perror("Error allocating memory");
//return ref. to empty string, so's prog wont crash
return "";
}
ipos = bpos = 0;
while (ipos < len)
{
//using inverted logic from original code....
if (!isdigit((int) (instr[ipos]))
&& !isalpha((int) instr[ipos]) && instr[ipos] != '_')
{
tmp = instr[ipos] / 16;
str[bpos++] = '%';
str[bpos++] = ((tmp < 10) ? (tmp + '0') : (tmp + 'A' - 10));
tmp = instr[ipos] % 16;
str[bpos++] = ((tmp < 10) ? (tmp + '0') : (tmp + 'A' - 10));
}
else
{
str[bpos++] = instr[ipos];
}
ipos++;
}
str[bpos] = '\0';
//free extra alloc'ed mem.
tmp = strlen(str);
str = (unsigned char *) realloc(str, tmp + 1);
return (str);
}
|