#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * url_encode(const char * str)
{
char * s = str;
char * t = NULL;
char * ret;
char * validChars = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz:/.?=_-$(){}~&";
char * isValidChar;
int lenght = 0;
// calcul de la taille de la chaine urlEncodée
do{
isValidChar = strchr(validChars, *s); // caractère valide?
if(!isValidChar)
lenght+=3; // %xx : 3 caractères
else
lenght++; // sinon un seul
}while(*++s); // avance d'un cran dans la chaine. Si on est pas à la fin, on continue...
s = str;
t = (char *)malloc(sizeof(char) * (lenght + 1)); // Allocation à la bonne taille
if(!t) exit(EXIT_FAILURE);
ret = t;
//encodage
do{
isValidChar = strchr(validChars, *s);
if(!isValidChar)
sprintf(t, "%%%2X", *s), t+=3;
else
sprintf(t, "%c", *s), t++;
}while(*++s);
*t = 0; // 0 final
return ret;
}
int main()
{
char * urlEncoded = url_encode("while(*str++)sqfqsfq ///\\ ");
printf("%s", urlEncoded);
free(urlEncoded); // Pensez à liberer l'espace alloué par l'encodeur!!
}