Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant parsing of query string in C

Tags:

c

refactoring

c99

I'm trying to parse a URL query string in C and I don't see how to do it 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 kept on having is that because of the strtok function anything that was seemed more intelligent to do before the last strtok function seemed to break the while loop.

like image 352
Rio Avatar asked Mar 12 '12 03:03

Rio


People also ask

What is query string in C?

A query string is an input parameter, specifying the statistical data to be retrieved. A query string is an input parameter to statistical C API functions which provide a result set token pointer. The string is a null-terminated, colon-separated list of IDs.

What is query string with example?

A query string commonly includes fields added to a base URL by a Web browser or other client application, for example as part of an HTML, choosing the appearance of a page, or jumping to positions in multimedia content.

What is a parse search query?

Parse. Query defines a query that is used to fetch Parse. Objects. The most common use case is finding all objects that match a query through the find method.


1 Answers

You either need to tailor complex and effective parser or settle with libraries that will do it for you.

uriparser should provide all you need (plus it supports unicode).

like image 59
Tomas Pruzina Avatar answered Oct 20 '22 23:10

Tomas Pruzina