I play with printf, and the idea is to write my_printf (...), which calls regular printf and sprintf, which sends the result to a special function. (I was thinking about sprintf, since it behaves the same as printf on most platforms).
My idea was to write a little macro that did this:
#define my_printf (X, Y ...) do {printf (X, ## Y); \
char * data = malloc (strlen (X) * sizeof (char)); \
sprintf (data, X, ## Y); \
other_print (data); \
free (data);} while (0)
But since sprintf can expand the string to a much larger size than X, this method breaks almost directly.
And just to add a number, malloc seems like the wrong way to attack the problem, since then I would just move the problem to the future and the day I want to print a large expression ...
Does anyone have a better idea on how to attack this problem? Or how can I find out how big the sprintf result will be?
Thanks Johan
Update: I forgot that printf returns the number of characters it prints, and since I already call printf in the macro, it was very easy to add an int that stores the number.
#define buf_printf (X, Y ...) do {int len = printf (X, ## Y); \
char * data = malloc ((len + 1) * sizeof (char)); \
sprintf (data, X, ## Y); \
other_print (data); \
free (data);} while (0)
: , ,
, .
, -, v- printf
(vprintf, vsprintf vsnprintf). , .
Johan