3

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?

Dilawar
  • 5,438
  • 9
  • 45
  • 58
  • At the end of this answer http://stackoverflow.com/a/19749019/225186 I wrote about the case of the `istringstream`, I guess something similar can be done for `ostringstream` – alfC Nov 24 '14 at 04:51

1 Answers1

1

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.

milleniumbug
  • 15,379
  • 3
  • 47
  • 71