/* strtok example */
#include <stdio.h>
#include <string.h>
int main ()
{
// in valid HTTP, each line of the header and the blank
// line must end with a carraige return and linefeed
char str[] = "HTTP/1.1 200 OK\r\n"
"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"
"Server: Apache/2.2.8 (Ubuntu) mod_ssl/2.2.8 OpenSSL/0.9.8g\r\n"
"Last-Modified: Sun, 26 Sep 2010 22:04:35 GMT\r\n"
"ETag: \"45b6-834-49130cc1182c0\"\r\n"
"Accept-Ranges: bytes\r\n"
"Content-Length: 12\r\n"
"Connection: close\r\n"
"Content-Type: text/html\r\n"
"\r\n"
"var1=red&var2=green&var3=up&var5=down&time=123443291&key=xmskwirrrr3";
// so, we want to find the blank line and then move to the next non-blank line
// no error checking has been done...
char *data = strstr(str,"\r\n\r\n")+strlen("\r\n\r\n");
printf("\nBody = %s\n", data);
// we will use an array of 1000 pairs of pointers
// so we can only handle 1000 KVP max...
char *pointers[1000][2] = {}; // default initialise all of them to MULL
// we need to keep track of the KVP number
// KVP starts at 0 and might go to 999
int KVP = 0;
// and a flag that indicates whether it is the key or value we are parsing
// key when key_value=0, value when key_value=1
#define KVP_KEY 0
#define KVP_VALUE 1
int key_value = KVP_KEY; // the key should be first
// first strtok the first value
// we need to do this because the first time strtok needs different parameters
pointers[KVP][key_value] = strtok(data,"=");
// loop through splitting it up and saving the pointers
// no error checking has been done...
while(KVP < 1000 && pointers[KVP][key_value] != NULL)
{
// ok, we need to update KVP and key_value
if (key_value == KVP_VALUE)
{
KVP++;
key_value = KVP_KEY;
pointers[KVP][key_value] = strtok(NULL,"=");
}
else // if (key_value == KVP_KEY)
{
key_value = KVP_VALUE;
pointers[KVP][key_value] = strtok(NULL,"&");
}
}
// now it should all be parsed
// let's print it all out
for(int i=0; i<KVP; i++)
{
printf("\nkey[%d] = %s\nvalue[%d] = %s\n",
i, pointers[i][KVP_KEY],
i, pointers[i][KVP_VALUE]);
}
return 0;
}