/* C playground by ChillerDragon File: test.c */ #include "stdio.h" #include "string.h" int char_allowed(unsigned char in) { switch(in) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '-': case '.': case '_': case '~': return 1; default: break; } return 0; } void str_url_escape(const char *pSrc, char *pDst, int Size) { int Index = 0; int Length = strlen(pSrc); while(Size-- && Length--) { unsigned char in = *pSrc; if(char_allowed(in)) pDst[Index++] = in; else { snprintf(&pDst[Index], sizeof(pDst), "%%%02x", in); Index += 3; } pSrc++; } pDst[Index] = 0; } int main() { char buf[16]; char esc[16]; strncpy(buf,"♪ x x", sizeof(buf)); str_url_escape(buf, esc, sizeof(esc)); printf("buf '%s'\n", buf); printf("esc '%s'\n", esc); strncpy(buf,"hello", sizeof(buf)); str_url_escape(buf, esc, sizeof(esc)); printf("buf '%s'\n", buf); printf("esc '%s'\n", esc); } /* $ gcc test.c && ./a.out * * buf 'x' * esc '%e2%99%aa%20x%20x' * buf 'hello' * esc 'hello' * */