<p>I am working with an open-source UNIX tool that is implemented in C++, and I need to change some code to get it to do what I want. I would like to make the smallest possible change in hopes of getting my patch accepted upstream. Solutions that are implementable in standard C++ and do not create more external dependencies are preferred.</p>

<p>Here is my problem. I have a C++ class -- let's call it "A" -- that currently uses fprintf() to print its heavily formatted data structures to a file pointer. In its print function, it also recursively calls the identically defined print functions of several member classes ("B" is an example). There is another class C that has a member std::string "foo" that needs to be set to the print() results of an instance of A. Think of it as a to_str() member function for A.</p>

<p>In pseudocode:</p>

<pre><code>class A {
public:
  ...

  void print(FILE* f);
  B b;

  ...  
};

...

void A::print(FILE *f)
{
  std::string s = "stuff";
  fprintf(f, "some %s", s);
  b.print(f);
}

class C {
  ...
  std::string foo;
  bool set_foo(std::str);
  ...
}

...

A a = new A();
C c = new C();

...

// wish i knew how to write A's to_str()
c.set_foo(a.to_str());
</code></pre>

<p>I should mention that C is fairly stable, but A and B (and the rest of A's dependents) are in a state of flux, so the less code changes necessary the better. The current print(FILE* F) interface also needs to be preserved. I have considered several approaches to implementing A::to_str(), each with advantages and disadvantages:</p>

<ol>
<li><p>Change the calls to fprintf() to sprintf()</p>

<ul>
<li>I wouldn't have to rewrite any format strings</li>
<li>print() could be reimplemented as: fprint(f, this.to_str());</li>
<li>But I would need to manually allocate char[]s, merge a lot of c strings , and finally convert the character array to a std::string</li>
</ul></li>
<li><p>Try to catch the results of a.print() in a string stream</p>

<ul>
<li>I would have to convert all of the format strings to &lt;&lt; output format. There are hundreds of fprintf()s to convert :-{</li>
<li>print() would have to be rewritten because there is no standard way that I know of to create an output stream from a UNIX file handle (though <a href="http://synflood.at/blog/index.php?/archives/456-One-word-of-warning-about-stdio_filebuf.html" rel="nofollow noreferrer">this guy says it may be possible</a>).</li>
</ul></li>
<li><p>Use Boost's string <a href="http://www.boost.org/doc/libs/1_36_0/libs/format/doc/format.html" rel="nofollow noreferrer">format library</a></p>

<ul>
<li>More external dependencies. Yuck.</li>
<li>Format's syntax is different enough from printf() to be annoying: </li>
</ul>

<p>printf(format_str, args) -> cout &lt;&lt; boost::format(format_str) % arg1 % arg2 % etc</p></li>
<li><p>Use Qt's <a href="https://doc.qt.io/qt-5/qstring.html#asprintf%3E" rel="nofollow noreferrer">QString::asprintf()</a></p>

<ul>
<li>A different external dependency.</li>
</ul></li>
</ol>

<p>So, have I exhausted all possible options? If so, which do you think is my best bet? If not, what have I overlooked?</p>

<p>Thanks.</p>

[{'answer_id': 69762, 'author': 'Assaf Lavie', 'author_id': 11208, 'author_profile': 'https://Stackoverflow.com/users/11208', 'pm_score': 0, 'selected': False, 'text': '<p>Is this about serialization? Or printing proper?\nIf the former, consider boost::serialization as well. It\'s all about "recursive" serialization of objects and sub-object.</p>\n'}, {'answer_id': 69765, 'author': 'bernhardrusch', 'author_id': 3056, 'author_profile': 'https://Stackoverflow.com/users/3056', 'pm_score': 5, 'selected': True, 'text': '<p>I am using #3: the boost string format library - but I have to admit that I\'ve never had any problem with the differences in format specifications.</p>\n\n<p>Works like a charm for me - and the external dependencies could be worse (a very stable library)</p>\n\n<p>Edited: adding an example how to use boost::format instead of printf:</p>\n\n<pre><code>sprintf(buffer, "This is a string with some %s and %d numbers", "strings", 42);\n</code></pre>\n\n<p>would be something like this with the boost::format library:</p>\n\n<pre><code>string = boost::str(boost::format("This is a string with some %s and %d numbers") %"strings" %42);\n</code></pre>\n\n<p>Hope this helps clarify the usage of boost::format    </p>\n\n<p>I\'ve used boost::format as a sprintf / printf replacement in  4 or 5 applications (writing formatted strings to files, or custom output to logfiles) and never had problems with format differences. There may be some (more or less obscure) format specifiers which are differently - but I never had a problem.</p>\n\n<p>In contrast I had some format specifications I couldn\'t really do with streams (as much as I remember)</p>\n'}, {'answer_id': 69767, 'author': 'Yann Ramin', 'author_id': 9167, 'author_profile': 'https://Stackoverflow.com/users/9167', 'pm_score': 2, 'selected': False, 'text': '<p>You can use std::string and iostreams with formatting, such as the setw() call and others in iomanip</p>\n'}, {'answer_id': 69911, 'author': 'Larry Gritz', 'author_id': 3832, 'author_profile': 'https://Stackoverflow.com/users/3832', 'pm_score': 5, 'selected': False, 'text': "<p>Here's the idiom I like for making functionality identical to 'sprintf', but returning a std::string, and immune to buffer overflow problems.  This code is part of an open source project that I'm writing (BSD license), so everybody feel free to use this as you wish.</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;cstdarg&gt;\n#include &lt;vector&gt;\n#include &lt;string&gt;\n\nstd::string\nformat (const char *fmt, ...)\n{\n    va_list ap;\n    va_start (ap, fmt);\n    std::string buf = vformat (fmt, ap);\n    va_end (ap);\n    return buf;\n}\n\n\n\nstd::string\nvformat (const char *fmt, va_list ap)\n{\n    // Allocate a buffer on the stack that's big enough for us almost\n    // all the time.\n    size_t size = 1024;\n    char buf[size];\n\n    // Try to vsnprintf into our buffer.\n    va_list apcopy;\n    va_copy (apcopy, ap);\n    int needed = vsnprintf (&amp;buf[0], size, fmt, ap);\n    // NB. On Windows, vsnprintf returns -1 if the string didn't fit the\n    // buffer.  On Linux &amp; OSX, it returns the length it would have needed.\n\n    if (needed &lt;= size &amp;&amp; needed &gt;= 0) {\n        // It fit fine the first time, we're done.\n        return std::string (&amp;buf[0]);\n    } else {\n        // vsnprintf reported that it wanted to write more characters\n        // than we allotted.  So do a malloc of the right size and try again.\n        // This doesn't happen very often if we chose our initial size\n        // well.\n        std::vector &lt;char&gt; buf;\n        size = needed;\n        buf.resize (size);\n        needed = vsnprintf (&amp;buf[0], size, fmt, apcopy);\n        return std::string (&amp;buf[0]);\n    }\n}\n</code></pre>\n\n<p>EDIT:  when I wrote this code, I had no idea that this required C99 conformance and that Windows (as well as older glibc) had different vsnprintf behavior, in which it returns -1 for failure, rather than a definitive measure of how much space is needed.  Here is my revised code, could everybody look it over and if you think it's ok, I will edit again to make that the only cost listed:</p>\n\n<pre><code>std::string\nStrutil::vformat (const char *fmt, va_list ap)\n{\n    // Allocate a buffer on the stack that's big enough for us almost\n    // all the time.  Be prepared to allocate dynamically if it doesn't fit.\n    size_t size = 1024;\n    char stackbuf[1024];\n    std::vector&lt;char&gt; dynamicbuf;\n    char *buf = &amp;stackbuf[0];\n    va_list ap_copy;\n\n    while (1) {\n        // Try to vsnprintf into our buffer.\n        va_copy(ap_copy, ap);\n        int needed = vsnprintf (buf, size, fmt, ap);\n        va_end(ap_copy);\n\n        // NB. C99 (which modern Linux and OS X follow) says vsnprintf\n        // failure returns the length it would have needed.  But older\n        // glibc and current Windows return -1 for failure, i.e., not\n        // telling us how much was needed.\n\n        if (needed &lt;= (int)size &amp;&amp; needed &gt;= 0) {\n            // It fit fine so we're done.\n            return std::string (buf, (size_t) needed);\n        }\n\n        // vsnprintf reported that it wanted to write more characters\n        // than we allotted.  So try again using a dynamic buffer.  This\n        // doesn't happen very often if we chose our initial size well.\n        size = (needed &gt; 0) ? (needed+1) : (size*2);\n        dynamicbuf.resize (size);\n        buf = &amp;dynamicbuf[0];\n    }\n}\n</code></pre>\n"}, {'answer_id': 69915, 'author': 'Jan de Vos', 'author_id': 11215, 'author_profile': 'https://Stackoverflow.com/users/11215', 'pm_score': 1, 'selected': False, 'text': '<p>The following might be an alternative solution:</p>\n\n<pre><code>void A::printto(ostream outputstream) {\n    char buffer[100];\n    string s = "stuff";\n    sprintf(buffer, "some %s", s);\n    outputstream &lt;&lt; buffer &lt;&lt; endl;\n    b.printto(outputstream);\n}\n</code></pre>\n\n<p>(<code>B::printto</code> similar), and define</p>\n\n<pre><code>void A::print(FILE *f) {\n    printto(ofstream(f));\n}\n\nstring A::to_str() {\n    ostringstream os;\n    printto(os);\n    return os.str();\n}\n</code></pre>\n\n<p>Of course, you should really use snprintf instead of sprintf to avoid buffer overflows. You could also selectively change the more risky sprintfs to &lt;&lt; format, to be safer and yet change as little as possible.</p>\n'}, {'answer_id': 70233, 'author': 'Kevin', 'author_id': 6386, 'author_profile': 'https://Stackoverflow.com/users/6386', 'pm_score': 1, 'selected': False, 'text': '<p>You should try the Loki library\'s SafeFormat header file (<a href="http://loki-lib.sourceforge.net/index.php?n=Idioms.Printf" rel="nofollow noreferrer">http://loki-lib.sourceforge.net/index.php?n=Idioms.Printf</a>).  It\'s similar to boost\'s string format library, but keeps the syntax of the printf(...) functions.</p>\n\n<p>I hope this helps!</p>\n'}, {'answer_id': 56267043, 'author': 'vitaut', 'author_id': 471164, 'author_profile': 'https://Stackoverflow.com/users/471164', 'pm_score': 2, 'selected': False, 'text': '<p><a href="https://github.com/fmtlib/fmt" rel="nofollow noreferrer">The {fmt} library</a> provides <code>fmt::sprintf</code> function that performs <code>printf</code>-compatible formatting (including positional arguments according to <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/printf.html" rel="nofollow noreferrer">POSIX specification</a>) and returns the result as <code>std::string</code>:</p>\n\n<pre><code>std::string s = fmt::sprintf("The answer is %d.", 42);\n</code></pre>\n\n<p><strong>Disclaimer</strong>: I\'m the author of this library.</p>\n'}, {'answer_id': 73359248, 'author': 'dgnuff', 'author_id': 4022617, 'author_profile': 'https://Stackoverflow.com/users/4022617', 'pm_score': 0, 'selected': False, 'text': "<p>Very very late to the party, but here's how I'd attack this problem.</p>\n<p>1: Use <code>pipe(2)</code> to open a pipe.</p>\n<p>2: Use <code>fdopen(3)</code> to convert the write fd from the pipe to a <code>FILE *</code>.</p>\n<p>3: Hand that <code>FILE *</code> to <code>A::print()</code>.</p>\n<p>4: Use <code>read(2)</code> to pull bufferloads of data, e.g. 1K or more at a time from the read fd.</p>\n<p>5: Append each bufferload of data to the target <code>std::string</code></p>\n<p>6: Repeat steps 4 and 5 as needed to complete the task.</p>\n"}]
['https://Stackoverflow.com/questions/69738', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8146/']