Skip to content

Instantly share code, notes, and snippets.

@EdgeCaseBerg
Last active December 25, 2015 01:29
Show Gist options
  • Save EdgeCaseBerg/6895190 to your computer and use it in GitHub Desktop.
Save EdgeCaseBerg/6895190 to your computer and use it in GitHub Desktop.
A URL string parsing function in C.
/*
Needs strmap http://pokristensson.com/strmap.html
*/
/*
* Parse the url and store values into the hash table
* returns the number of values successfully placed into the hashtable
*/
int parseURL(char * url, int urlLength, StrMap * table){
int i;
int j;
int pairCounter;
char keyBuff[256];
char valBuff[256];
bzero(keyBuff,sizeof keyBuff);
bzero(valBuff,sizeof valBuff);
if(url == NULL)
return 0;
if(table == NULL)
return -1; /* Err ... */
pairCounter = 0;
/* Find ? */
for(i=0; url[i] != '\0' && i < urlLength; ++i)
if(url[i] == '?')
break;
while(url[i] != '\0' && i < urlLength){
for(j=0,i++; url[i] != '=' && url[i] != '\0' && i < urlLength; ++i)
keyBuff[j++] = url[i];
keyBuff[j] = '\0';
for(j=0,i++; strlen(keyBuff) > 0 && url[i] != '&' && url[i] != '\0' && i < urlLength; ++i)
valBuff[j++] = url[i];
valBuff[j] = '\0';
fprintf(stderr, "valBuff:%zu, keyBuff:%zu\n", strlen(valBuff), strlen(keyBuff));
if(strlen(valBuff) > 0 && strlen(keyBuff) > 0){
/* Place values into table */
fprintf(stderr, "%s=>%s\n", keyBuff, valBuff);
if(sm_put(table, keyBuff, valBuff) == 0)
fprintf(stderr, "Failed to copy parameters into hash table while parsing url\n");
else
pairCounter++;
}
/* reset the buffers */
bzero(keyBuff,sizeof keyBuff);
bzero(valBuff,sizeof valBuff);
}
return pairCounter;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment