RosettaCodeData/Task/URL-decoding/C/url-decoding.c

41 lines
711 B
C
Raw Permalink Normal View History

2023-07-01 11:58:00 -04:00
#include <stdio.h>
#include <string.h>
inline int ishex(int x)
{
2026-04-30 12:34:36 -04:00
return (x >= '0' && x <= '9') ||
(x >= 'a' && x <= 'f') ||
(x >= 'A' && x <= 'F');
2023-07-01 11:58:00 -04:00
}
int decode(const char *s, char *dec)
{
2026-04-30 12:34:36 -04:00
char *o;
const char *end = s + strlen(s);
int c;
for (o = dec; s <= end; o++) {
c = *s++;
if (c == '+') c = ' ';
else if (c == '%' && ( !ishex(*s++) ||
!ishex(*s++) ||
!sscanf(s - 2, "%2x", &c)))
return -1;
if (dec) *o = c;
}
return o - dec;
2023-07-01 11:58:00 -04:00
}
int main()
{
2026-04-30 12:34:36 -04:00
const char *url = "http%3A%2F%2ffoo+bar%2fabcd";
char out[strlen(url) + 1];
2023-07-01 11:58:00 -04:00
2026-04-30 12:34:36 -04:00
printf("length: %d\n", decode(url, 0));
puts(decode(url, out) < 0 ? "bad string" : out);
2023-07-01 11:58:00 -04:00
2026-04-30 12:34:36 -04:00
return 0;
2023-07-01 11:58:00 -04:00
}