c++ - ofstream doesn't write buffer to file -


I am trying to write the contents of the buf pointer to a file created by the offstream.

Some reason the file is empty, but the content of the buff is never empty ... what am I doing wrong?

  void DLog :: log (const char * fmt, ...) {Va_list varptr; Va_start (varptr, fmt); Int n = :: _ vscprintf (fmt, varptr); Char * buf = new four [N + 1]; :: vsprintf (buff, fmt, variety); Va_end (varptr); If (! M_filename.empty ()) {std :: ofstream ofstr (m_filename.c_str (), ios :: out); Ofstr & lt; & Lt; * Buf; // The contents of the bluff are not empty, although there is nothing in the file ?? Ofstr.close (); } Remove [] buf; }  

Getting rid of hair stuff can solve many problems, such as manual Allocation Management

Never use new T [n] in your code: instead of std :: vector & lt; T & gt; V (N); . Just this alone can solve your problem, because the pointer is not like this:

  void DLog :: log (const char * fmt, ...) {va_list varptr; Va_start (varptr, fmt); Int n = :: _ vscprintf (fmt, varptr); Std :: vector & lt; Four & gt; Buf (n + 1); :: vs printprint (& amp; buff [0], FMT, VRTTR); Va_end (varptr); If (! M_filename.empty ()) {std :: ofstream ofstr (m_filename.c_str (), ios :: out); If (! Ofstr) {// Not to open, report some error here} // Copy each letter of the stream std :: copy (buf.begin (), buf.end (), std :: ostream_iterator & Lt; char & gt; (ofstr); // no need to stop it, it is done automatically) // There is no need to remember to delete}  

It is very easy to read and maintain Note would also be better std :: string buf (n + 1); , then you can just type ofstr & lt; & Lt; Buf; . Sadly, std :: string does not currently require its elements to be stored narrowly, such as std :: vector . This means that the line with the AND [0] is not guaranteed to work, he said, I suspect you will get an implementation where this will not work. However, it is reasonably better to maintain guaranteed behavior.

However, I indicate that you are defending the pointer, though.


Comments