Skip to content

Instantly share code, notes, and snippets.

@deltheil
Created March 25, 2013 09:48
Show Gist options
  • Save deltheil/5236049 to your computer and use it in GitHub Desktop.
Save deltheil/5236049 to your computer and use it in GitHub Desktop.
Append character strings with asprintf(3)
#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