Created
March 25, 2013 09:48
-
-
Save deltheil/5236049 to your computer and use it in GitHub Desktop.
Append character strings with asprintf(3)
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
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
static int append(char **str, const char *buf, int size); | |
int main(void) { | |
char *str = NULL; | |
append(&str, "this", 4); | |
append(&str, " is", 3); | |
append(&str, " a ", 3); | |
append(&str, "test", 4); | |
printf("%s\n", str); | |
free(str); | |
return 0; | |
} | |
static int append(char **str, const char *buf, int size) { | |
char *nstr; | |
if (*str == NULL) { | |
nstr = malloc(size + 1); | |
memcpy(nstr, buf, size); | |
nstr[size] = '\0'; | |
} | |
else { | |
if (asprintf(&nstr, "%s%.*s", *str, size, buf) == -1) return -1; | |
free(*str); | |
} | |
*str = nstr; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment