You can force the stream to empty its buffer into an output file, or to refill its buffer from an input file. This is done through the stream buffer's public member function pubsync(). Typically, you call pubsync() indirectly through functions of the stream layer. Input streams and output streams have different member functions that implicitly call pubsync().
Output streams have a flush() function that writes the buffer content to the file. In case of failure, badbit is set or an exception thrown, depending on the exception mask.
std::ofstream ofstr("/tmp/fil");
ofstr << "Hello "; //1
ofstr << "World!\n";
ofstr.flush(); //2
Keep in mind that flushing is a time-consuming operation. The member function flush() not only writes the buffer content to the file; it may also reread the buffer in order to maintain the current file position. For the sake of performance, you should avoid inadvertent flushing, as when the std::endl manipulator calls flush() on inserting the end-of-line character. (See Section 28.3.2.)
Input streams define the sync() member function. It forces the stream to access the external device and refill its buffer, beginning with the current file position. In the case of input streams, the behavior of sync() is implementation-defined, that is, not standardized. The traditional iostreams had a sync() function that did the expected synchronization, that is, refilling the buffer beginning with the current file position.
The example below demonstrates the principle theoretically. In real life, however, the two streams might belong to two separate processes. (For example, if two processes communcate through a shared file.) It should be noted that the exact behavior of the example below depends on the size of the internal buffers and other inherently implementation-specific parameters.
std::ofstream ofstr("/tmp/fil");
std::ifstream ifstr("/tmp/fil");
std::string s;
ofstr << "Hello ";
std::ofstream::pos_type p = ofstr.tellp();
ofstr << "World!\n" << std::flush;
ifstr >> s; //1
ofstr.seekp(p);
ofstr << "Peter!" << std::flush; //2
ifstr >> s; //3
ofstr << " Happy Birthday!\n" << std::flush; //4
ifstr >> s; //5
ifstr.sync(); //6
ifstr >> s;
NOTE -- If you must synchronize several streams that share a file, it is advisable to call the sync() function after each output operation and before each input operation.