5

I'm writing a C/CGI web application. Is there a library to parse a query string into something like a GHashTable? I could write my own but it certainly doesn't seem to be worth the effort to reinvent the wheel.

3 Answers 3

3

The uriparser library can parse query strings into key-value pairs.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! As an added bonus for me, the Ubuntu repositories conveniently include liburiparser1/liburiparser-dev.
2

If you're really writing C and the set of keys is known, you'd do much better to store the values in a struct instead of some bloated hash table. Have a static const table of:

  • key name
  • type (integer/string is probably sufficient)
  • offset in struct (using offsetof macro)

and use that to parse the query string and fill in the struct.

2 Comments

+1 from me, but wouldn't a hash table lookup be faster than walking through each struct and comparing strings?
@Delan: for initially looking up the types/offsets, a hash would be more efficient than a linear search through the possible key names. You could sort the key names to get logarithmic time, or better yet (since the list of key names is known in advance) use a perfect hash chosen for them. This gives better performance, zero memory usage (all const tables), and less code complexity.
0

You may find usefull the ap_getword functions family from the Apache Portable Runtime (apr) library.

Most of the string parsing routines belong to the ap_getword* family, which together provide functionality similar to the Perl split() function. Each member of this family is able to extract a word from a string, splitting the text on delimiters such as whitespace or commas. Unlike Perl split(), in which the entire string is split at once and the pieces are returned in a list, the ap_getword* functions operate on one word at a time. The function returns the next word each time it's called and keeps track of where it's been by bumping up a pointer.

You may search google for "ap_getword(r->pool" "httpd.h" and find some relevant source code to learn from.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.