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