appendsnprintf.c (868B)
1 #include <stdarg.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <string.h> 5 6 //# this function will generate the fmt specifier for appendsnprintf, should only be used for this use case 7 char *genfmt(char *buf, char *fmt){ 8 int len = strlen(buf) + strlen(fmt) + 1; 9 char *out = malloc(len); 10 11 int j = 0, i = 0; 12 while (buf[i] != '\0'){ 13 out[i] = buf[i]; 14 i++; 15 } 16 while (fmt[j] != '\0'){ 17 out[i] = fmt[j]; 18 i++; 19 j++; 20 } 21 out[i] = '\0'; 22 return out; 23 } 24 25 //# this function will append size number of bytes, onto the end of buf, a format string in the form of vaargs 26 char *appendsnprintf(char *buf, int size, char *format, ...){ 27 va_list ap; 28 char *outputbuf = malloc(size); 29 va_start(ap, format); 30 char *fmt = genfmt(buf, format); 31 vsnprintf(outputbuf, size, fmt, ap); 32 free(fmt); 33 34 buf = realloc(outputbuf, strlen(outputbuf) + 1); 35 va_end(ap); 36 37 return buf; 38 }