C ++ - from stream is not output to file until I close the program

I have the following code:

   ofstream mOutFile.open(logPath, ios_base::app);
   string lBuilder;

   lBuilder.append("Date: ");
   lBuilder.append("Log Message:\n");

   int lSize = lBuilder.size();
   char* lBuffer = new char[lSize];
   int index = 0;
   for each (char c in lBuilder)
      lBuffer[index++] = c;

   mOutFile.write(lBuffer, lSize);


Unfortunately, until I close the application (I assume that closing the stream will work as well), the output will not be written to a text file. I know that maybe I can close and reopen the stream and everything will "just work", but that seems like a stupid and wrong solution. What am I doing wrong here?

I've also tried the following options based on other questions I found here, but these solutions didn't work:

mOutputFile << flush;
mOutputFile << endl;


Thanks in advance for any help on this.

edit Everything in this code works with visual C ++, it builds and works fine, except that the file is not written until the stream is closed, even if I press flash. Also, I switched from using the <operator to char * and .write () to see if something is different.


source to share

2 answers

I ended up just "running" the job by closing and reopening the stream after the write operation.

mOutputFile << "all of my text" << endl;


EDIT . After trying to force flash on several other systems, it looks like something just isn't working correctly on my development machine. Not good news, but at least the solution above seems to fire when programmatically clearing the stream fails. I'm not sure about the meanings of the above code though, if anyone wants to call back if there are consequences of closing and reopening a stream like this.



std::ofstream file(logPath, ios_base::app);

file << "========================================================\n"
     << "Date: " << asctime(timeinfo)
     << "\nLog Message:\n" << toLog
     << "\n========================================================\n\n"
     << std::flush; 
     //if you want to force it write to the file it will also flush when the the file object is destroyed
//file will close itself


Not only is this easier to read, it will probably be faster than your method +, this is a more standard estimate



All Articles