Wrote to a File Using Std::Wofstream. the File Remained Empty

ofstream doesn't write buffer to file

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 use std::vector<T> v(N);. Simply this alone might solve your problem, because the pointer stuff isn't in the way:

void DLog::Log(const char *fmt, ...)
va_list varptr;
va_start(varptr, fmt);

int n = ::_vscprintf(fmt, varptr);
std::vector<char> buf(n + 1);

::vsprintf(&buf[0], fmt, 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<char>(ofstr));

// no need to close, it's done automatically

// no need to remember to delete

Much easier to read and maintain. Note even better would be a std::string buf(n + 1);, then you could just do ofstr << buf;. Sadly, std::string isn't currently required to store its elements contiguously, like std::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.

Writing to file results in empty file

Trying to call open on an already open file stream puts the stream in a failed state.

Just change

ofstream newFile(fileName);         // create new file with same name
newFile.open(fileName, ios::app);


ofstream newFile(fileName, ios::app); 


void open(const char* s, ios_base::openmode mode = ios_base::out);

Effects: Calls rdbuf()->open(s, mode | ios_base::out). If that
function does not return a null pointer calls clear(), otherwise calls
(which may throw ios_base::failure (


basic_filebuf<charT,traits>* open(const char* s, ios_base::openmode mode);

Effects: If is_open() != false, returns a null pointer. [...]

bool is_open() const;

Returns: true if a previous call to open succeeded (returned a
non-null value) and there has been no intervening call to close.

static ofstream will create a file but never write to it?

The issue was the proper destruction of the global object that was not guaranteed. By adding the following to my code:

out_file << data << std::flush;

It all works as expected.

wofstream only creates an empty file c++

std::wofstream outFile(convertedPlatformPathandFilename);

This creates a new file, and opens it for writing.


This attempts to open the same file stream for writing a second time. Because the file stream is already open, this is an error. The error sets the stream into a failed state, and all attempts to write to the stream will now fail.

This is how you end up with an empty output file. It gets created, and a duplicate, second attempt to open the same file stream object puts it into error state.

Related Topics

Leave a reply