You can achieve a kind of automatic synchronization for output files by using the format flag ios_base::unitbuf. It causes an output stream to flush its buffer after each output operation as follows:
std::ofstream ostr("/tmp/fil"); std::ifstream istr("/tmp/fil"); ostr << std::ios_base::unitbuf; //1 while (some_condition) { ostr << "... some output ..."; //2 // process the output istr >> s; // ... }
//1 | Set the unitbuf format flag. |
//2 | After each insertion into the file /tmp/fil, the buffer is automatically flushed, and the output is available to other streams that read from the same file. |
Since it is not overly efficient to flush after every single token that is inserted, you might consider switching off the unitbuf flag for a lengthy output that is not supposed to be read partially.
ostr.unsetf(std::ios_base::unitbuf); //1 ostr << "... some lengthy and complicated output ..."; ostr.flush().setf(std::ios_base::unitbuf); //2
//1 | Switch off the unitbuf flag. Alternatively, using manipulators, you can use ostr << std::ios_base::nounitbuf; |
//2 | Flush the buffer and switch on the unitbuf flag again. Alternatively, you can use the std::ios_base::flush and std::ios::base::unitbuf manipulators. |