Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Many problems can be solved by getting rid of the hairy stuff, like manual allocation management. </p> <p>Never use <code>new T[N]</code> in your code: instead use <code>std::vector&lt;T&gt; v(N);</code>. Simply this alone might solve your problem, because the pointer stuff isn't in the way:</p> <pre><code>void DLog::Log(const char *fmt, ...) { va_list varptr; va_start(varptr, fmt); int n = ::_vscprintf(fmt, varptr); std::vector&lt;char&gt; buf(n + 1); ::vsprintf(&amp;buf[0], fmt, varptr); va_end(varptr); if (!m_filename.empty()) { std::ofstream ofstr(m_filename.c_str(), ios::out); if (!ofstr) { // didn't open, do some error reporting here } // copy each character to the stream std::copy(buf.begin(), buf.end(), std::ostream_iterator&lt;char&gt;(ofstr)); // no need to close, it's done automatically } // no need to remember to delete } </code></pre> <p>Much easier to read and maintain. Note even better would be a <code>std::string buf(n + 1);</code>, then you could just do <code>ofstr &lt;&lt; buf;</code>. Sadly, <code>std::string</code> isn't currently required to store its elements contiguously, like <code>std::vector</code>. This means the line with <code>&amp;buf[0]</code> isn't guaranteed to work. That said, I doubt you'll find an implementation where it wouldn't work. Still, it's arguably better to maintain guaranteed behavior.</p> <p>I do <a href="https://stackoverflow.com/questions/3279733/ofstream-doesnt-write-buffer-to-file/3279778#3279778">suspect</a> the <a href="https://stackoverflow.com/questions/3279733/ofstream-doesnt-write-buffer-to-file/3279814#3279814">issue</a> was you dereferencing the pointer, though.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload