I’m trying to write the contents of buf pointer to the file created by ofstream.
For some reason the file is empty, however the contents of buf 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 char[n + 1];
::vsprintf(buf, fmt, varptr);
va_end(varptr);
if (!m_filename.empty())
{
std::ofstream ofstr(m_filename.c_str(), ios::out);
ofstr << *buf; // contents of *buf are NEVER empty, however nothing is in file??
ofstr.close();
}
delete [] buf;
}
Many problems can be solved by getting rid of the hairy stuff, like manual allocation management.
Never use
new T[N]in your code: instead usestd::vector<T> v(N);. Simply this alone might solve your problem, because the pointer stuff isn’t in the way:Much easier to read and maintain. Note even better would be a
std::string buf(n + 1);, then you could just doofstr << buf;. Sadly,std::stringisn’t currently required to store its elements contiguously, likestd::vector. This means the line with&buf[0]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.I do suspect the issue was you dereferencing the pointer, though.