Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make fprintf to write to std::stringstream

Function fprintf writes to FILE*. I have a debugPrint function which writes to stringstream. I don't want to change my function for it is used at many places and it would break the code.

How can I pass a stringstream to fprintf?

UPDATE : Can I wrap the stringstream to a FILE and unwrap back?

like image 203
Dilawar Avatar asked Sep 20 '26 08:09

Dilawar


1 Answers

You can't "pass" the ostream to fprintf. The FILE structure is platform dependent.

This is probably not the best way, but you can however create an evil macro:

#undef fprintf
#define fprintf my_fprintf

And you can create two my_fprintfs, one that takes FILE*, and another that takes std::stringstream& as argument.

You can avoid the macro by simply calling my_fprintf directly, but you have to modify the call site.

You can't "wrap stringstream in FILE*" portably, but there are some system specific ways. If that's what you after, then Linux for example has fopencookie() which take function pointers to read/write functions. You could then create functions that wrap std::stringstream.

like image 128
milleniumbug Avatar answered Sep 23 '26 03:09

milleniumbug