
Untitled
By: a guest on Feb 12th, 2012 | syntax:
None | size: 1.76 KB | hits: 26 | expires: Never
/*
CGI Helper functions
*/
/*
todo: - escape mysql string
- unescape http shit
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//Function declarations
size_t get_var(char *haystack, char *name, char **result);
void* zalloc(size_t num, size_t type);
int main()
{
char *buffer;
int num;
num = get_var("pretty=nice&parsing=function&findme=hik0pp&hello=bye", "findme", &buffer);
printf("%d\n", num);
printf("%s\n", buffer);
return 0;
}
size_t get_var(char *haystack, char *needle, char **result)
{
char *buffer;
char *search;
char *res;
char *found;
//create copies to work with
buffer = zalloc(strlen(haystack) + 1, sizeof(char)); //Copy of haystack to rape
search = zalloc(strlen(needle) + 2, sizeof(char)); //'needle' + '='
strcpy(buffer, haystack);
sprintf(search, "%s=", needle);
//Find the needle
res = strstr(buffer, search);
if(res == NULL)
{
*result = NULL;
return 0;
}
//Go past the =
res += strlen(search);
found = res;
//Look for the end of the value
while(res[0] != 0 && res[0] != '&')
{
res++;
}
//Make res[0] into a null byte, in case its &
res[0] = 0;
//Create the result buffer
*result = zalloc(strlen(found) + 1, sizeof(char));
strcpy(*result, found);
printf("%s\n", *result);
//Free the buffers so there is no leak
free(buffer);
free(search);
//Return length
return strlen(*result);
}
//Zero alloc, allocates, zeros and error checks <3
void* zalloc(size_t num, size_t type)
{
void *return_buffer;
return_buffer = calloc(num, type); //allocate it
if(return_buffer == NULL)
{
//Out of memory, hard quit
exit(-1);
}
memset(return_buffer, 0, num * type); //ZERO the memory
return return_buffer;
}