Skip to content

Instantly share code, notes, and snippets.

@deltheil
Created March 7, 2013 09:41
Show Gist options
  • Save deltheil/5106802 to your computer and use it in GitHub Desktop.
Save deltheil/5106802 to your computer and use it in GitHub Desktop.
Format C string with length pre-computation.
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
static char *mysprintf(const char *format, ...);
int main(void) {
char *str = mysprintf("%s fmt with various values: PI ~= %.2f", "Test", 3.14);
printf("%s (len = %zd)\n", str, strlen(str));
free(str);
return 0;
}
static char *mysprintf(const char *format, ...) {
va_list ap;
char *fstr = NULL;
va_start(ap, format);
int len = vsnprintf(NULL, 0, format, ap);
va_end(ap);
fstr = malloc(len + 1);
va_start(ap, format);
if (fstr) vsnprintf(fstr, len + 1, format, ap);
va_end(ap);
return fstr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment