Created
March 7, 2013 09:41
-
-
Save deltheil/5106802 to your computer and use it in GitHub Desktop.
Format C string with length pre-computation.
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 <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