Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - ofstream doesn't output to file until I close the program

I have the following code:

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

   lBuilder.append("========================================================\n");
   lBuilder.append("Date: ");
   lBuilder.append(asctime(timeinfo));
   lBuilder.append("\n");
   lBuilder.append("Log Message:\n");
   lBuilder.append(toLog);
   lBuilder.append("\n");
   lBuilder.append("========================================================\n\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);
   mOutFile.flush();

Unfortunately, until I close the app (I assume that closing the ofstream would work as well) the output does not get written to the text file. I know I could probably close and reopen the stream and everything will "just work" but that seems like a silly and incorrect solution. What am I doing wrong here?

I have also tried the following variations based on other questions I have found here, but these solutions did not work:

mOutputFile << flush;
mOutputFile << endl;

Thanks in advance for any assistance on this.

edit Everything in this code is working visual c++, it builds and works fine except the file is not written to until the stream is closed, even if I force a flush. Also, I switched from using the << operator to the char * and .write () to see if anything behaved differently.

like image 441
Bender the Greatest Avatar asked Mar 09 '12 21:03

Bender the Greatest


2 Answers

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

This is not only easier to read but it will probably also be faster than your method + it is a more standard appraoch

like image 130
111111 Avatar answered Sep 28 '22 07:09

111111


I ended up just "making it work" by closing and reopening the stream after the write operation.

mOutputFile << "all of my text" << endl;
mOutputFile.close();
mOutputFile.open(mLogPath);

EDIT After trying out forcing the flush on a few other systems, it looks like something just isn't performing correctly on my development machine. Not good news but at least the above solution seems to work when programmatically flushing the ofstream fails. I am not sure of the implications of the above code though, so if anyone wants to chime in if there are implications of closing and reopening the stream like this.

like image 33
Bender the Greatest Avatar answered Sep 28 '22 06:09

Bender the Greatest