A pure (windows) “C” version of urlencode

Internet, Software

This is a windows pure C language version of a urlencode() function.
Sometimes, when I need simple tools and self contained windows EXEs (“just run it”, no “dll”s to copy or register), I find it simpler to code in C than in other languages. Particularly when you want to link with specialized libraries available only in C. So, I scavenged the web for a ready to use urlencode routine and found nothing really useable out of the box. Although this one is largely inspired by what I found.

// Warning !! caller must free the string TCHAR pointer
// source (NOT endorsed; that anyway doesn't work): http://www.silverwolf.co.kr/4890?ckattempt=1
TCHAR *urlencode(TCHAR *str)
{
  TCHAR *encstr, buf[2 + 1];
  TCHAR c;
  int i, j;

  if (str == NULL) return NULL;
  if ((encstr = (TCHAR *)malloc((_tcslen(str) * sizeof(TCHAR)* 3) + sizeof(TCHAR))) == NULL)
    return NULL;

  for (i = j = 0; str[i]; i++)
  {
    c = (TCHAR)str[i];
    if( ((c >= '0') && (c <= '9')) || ((c >= 'A') && (c <= 'Z')) ||
        ((c >= 'a') && (c <= 'z')) || ((c == '@') || (c == '.') || 
         (c == '/') || (c == '\\') || (c == '-') || (c == '_') || 
         (c == ':') || (c == '~'))) {
      encstr[j++] = c;
    }
    else
    {
      wsprintf(buf, _T("%02x"), c);
      encstr[j++] = _T('%');
      encstr[j++] = buf[0];
      encstr[j++] = buf[1];
    }
  }
  encstr[j] = _T('\0');

  return encstr;
}

Example:

//...
  lpEncodedURL = urlencode(lpURL);
  if (NULL == lpEncodedURL) {
    // return AAARGH, memory problem with malloc();
  }
//...
  free(lpEncodedURL);
//...

Enjoy !

Comments on this entry are closed.