Created
September 18, 2011 17:19
-
-
Save kisom/1225294 to your computer and use it in GitHub Desktop.
C function to split a buffer into a char ** containing each line.
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) project | |
* | |
* from twitter (@kyleisom): | |
* '"so a char * goes to a char ** where each char * in the char ** is a line | |
* in the first char *" - me explaining my C algorithm to @qb1t' | |
*/ | |
/* | |
* Internal function used to split a buffer read from file into separate | |
* lines. | |
* arguments: | |
* - buffer contains the contents of the file | |
* - line_buffer has been allocated with a sufficient number of | |
* char *s (i suggest counting the number of newlines and | |
* using that as a reference for the largest number of lines you | |
* would need.) Note that the individual char * elements are | |
* calloc'd in here, it just needs to be calloc'd as an array | |
* of char *s. | |
* returns: | |
* EXIT_SUCCESS if all went well | |
* EXIT_FAILURE if things went bad (primarily if memory could not be | |
* allocated) | |
*/ | |
int | |
split_lines(char *buffer, char **line_buffer) | |
{ | |
size_t cur_line, i; | |
char *l_start, *l_end; | |
i = 0; | |
cur_line = 0; | |
l_start = buffer; | |
l_end = buffer; | |
while ('\0' != l_end[1]) { | |
/* Increment pointer to end of line after assignment. */ | |
l_end++; | |
if ('\n' == l_end[0]) { | |
/* We don't want to process empty lines. */ | |
if ((size_t)(l_end - l_start) > 1) { | |
line_buffer[cur_line] = calloc(LURKER_MAX_CONFIG_LINE_SZ, | |
sizeof(char)); | |
if (NULL == line_buffer[cur_line]) | |
return EXIT_FAILURE; | |
/* | |
* STRCPY is a macro that expands to strncpy on linux | |
* and strlcpy on real systems. | |
*/ | |
STRCPY(line_buffer[cur_line++], l_start, | |
(size_t)(l_end - l_start)); | |
l_start = ++l_end; | |
} | |
else | |
/* Look for double newlines and skip them. */ | |
if ((1 == (size_t)(l_end - l_start)) && | |
(l_start[0] == l_end[0])) | |
l_start = ++l_end; | |
} | |
} | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment