I am trying to parse a URL query string in C and I do not see how to do this elegantly. Any hints or suggestions would be greatly appreciated:
static void readParams(char * string, char * param, char * value) { char arg[100] = {0}; // Not elegant, brittle char value2[1024] = {0}; sscanf(string, "%[^=]=%s", arg, value2); strcpy(param, arg); strcpy(value, value2); } char * contents = "username=ted&age=25"; char * splitted = strtok (contents,"&"); char * username; char * age; while (splitted != NULL) { char param[100]; // Not elegant, brittle char value[100]; char * t_str = strdup(splitted); readParams(t_str, param, value); if (strcmp(param, "username") == 0) { username = strdup(value); } if (strcmp(param, "age") == 0) { age = strdup(value); // This is a string, can do atoi } splitted = strtok (NULL, "&"); }
The problem I ran into is that because of the strtok
everything that seemed more reasonable until the last strtok
seemed to break the while loop.
source share