I need the target length of how many characters I will need in a *printf
function. My scenario is a logging facility that should finally create a string (what happens to it is irrelevant, it must end in a char *
).
I currently have this:
void log(char *format, ...)
{
char *full_message, *message;
FILE *nullfile;
va_list args;
va_start(args, format);
nullfile = fopen("/dev/null", "w");
message_len = vfprintf(nullfile, format, args) + 1;
fclose(nullfile);
va_end(args);
va_start(args, format);
message = malloc(message_len);
vsnprintf(message, message_len, format, args);
va_end(args);
// now do something with the final message
}
That works like a charm, but it seems overly complicated. Is there an easier way? Something that makes more sense.
Additional detail: I finally format the string further and dump it into an OpenSSL BIO
, so its not as easy as using vfprinf
.