All pastes #435839 Raw Edit

Miscellany

public text v1 · immutable
·published 2007-04-12 05:09 UTC
rendered paste body
//URL ENCODING
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;
}