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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
// 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:
1 2 3 4 5 6 7 |
//... lpEncodedURL = urlencode(lpURL); if (NULL == lpEncodedURL) { // return AAARGH, memory problem with malloc(); } //... free(lpEncodedURL); //... |
Enjoy !
Recent Comments