Created
September 20, 2011 18:29
-
-
Save kisom/1229891 to your computer and use it in GitHub Desktop.
C function to parse a simple "command: value" line into command and value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* written by kyle isom <[email protected]> | |
* license: isc / public domain dual license | |
* one of the functions i wrote for the lurker project | |
* (https://github.com/kisom/lurker) | |
* | |
* C function to split a line into command and value | |
*/ | |
/* | |
* Internal function to split a line into command and value | |
* arguments: | |
* - line: a line of text. in lurker, this is already guaranteed | |
* to be an allocated buffer with a line of text in it, and it | |
* is guaranteed not to have any newlines or carriage returns. | |
* if it is used elsewhere, it may need to be tweaked. | |
* - a pointer to a char pointer, this should be a char * in the | |
* caller. this will be allocated with the proper amount of memory | |
* and needs to be freed by the caller. this is used to store the | |
* command. | |
* - a pointer to a char pointer, this should be a char * in the | |
* caller. this will be allocated with the proper amount of memory | |
* and needs to be freed by the caller. this is used to store the | |
* value of the command. | |
* - a const char that contains the character used to demarcate command | |
* and value. | |
* returns: | |
* - EXIT_FAILURE on function failure (i.e. malloc error, or the | |
* line doesn't look like a command) | |
* - EXIT_SUCCESS if it looks like all went well | |
* cleaning up: pass cmd and val to destroy_simple(cmd, val) to properly free | |
* the memory. | |
* | |
* an example line looks like "server: irc.example.net", cmd will have "server" | |
* and val will have "irc.example.net". | |
*/ | |
int | |
parse_simple(char *line, char *cmd, char *val, const char split_char) | |
{ | |
char *cmdval; | |
cmdval = strdup(line); | |
if (NULL == cmdval) | |
return EXIT_FAILURE; | |
cmd = cmdval; | |
val = strchr(cmdval, (int)split_char); | |
if (0 == strlen(val)) { | |
destroy_simple(cmd, val); | |
return EXIT_FAILURE; | |
} | |
cmdval = NULL; | |
val[0] = '\0'; | |
val++; | |
return EXIT_SUCCESS; | |
} | |
void | |
destroy_simple(char *cmd, char *val) | |
{ | |
if ('\0' != val[0]) | |
(--val)[0] = 'A'; /* Pick a char, any char. */ | |
free(cmd); | |
cmd = NULL; | |
val = NULL; | |
return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment