Created
September 20, 2011 15:01
-
-
Save kisom/1229331 to your computer and use it in GitHub Desktop.
C function to split a line into cmd, val
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 | |
* | |
* 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_ch) | |
{ | |
size_t line_sz, i; | |
i = 0; | |
line_sz = strlen(line); | |
for (i = 0; '\0' != line[i]; ++i) | |
if (split_ch == line[i]) | |
break; | |
if (i == line_sz) | |
return EXIT_FAILURE; | |
*cmd = calloc(i + 1, sizeof(char)); | |
*val = calloc(line_sz - i + 1, sizeof(char)); | |
if ((NULL == cmd) || (NULL == val)) | |
return EXIT_FAILURE; | |
/* Increment i after copy to move past the split character. */ | |
STRCPY(*cmd, line, i++); | |
STRCPY(*val, line +i, line_sz - i); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment