Another mechanism for automatic synchronization in certain cases is tying a stream to an output stream, as demonstrated in the code below. All input or output operations flush the tied stream's buffer before they perform the actual operation.
std::ofstream ostr("/tmp/fil"); std::ifstream istr("/tmp/fil"); std::ostream* old_tie = istr.tie(&ostr); //1 while (some_condition) { ostr << "... some output ..."; std::string s; while (istr >> s) //2 // process input ; } istr.tie(old_tie); //3
//1 | The input stream istr is tied to the output stream ostr. The tie() member function returns a pointer to the previously tied output stream, or 0 if no output stream is tied. |
//2 | Before any input is done, the tied output stream's buffer is flushed so that the result of previous output operations to ostr is available in the external file /tmp/fil. |
//3 | The previous tie is restored. |