function
<ostream> <iostream>

std::flush

for ostream
ostream& flush (ostream& os);
basic template
template <class charT, class traits>
basic_ostream<charT,traits>& flush (basic_ostream<charT,traits>& os);
Flush stream buffer
Synchronizes the associated stream buffer with its controlled output sequence.

For stream buffer objects that implement intermediate buffers, this function requests all characters to be written to the controlled sequence.

Its behavior is equivalent to calling os's member function flush.

A member function with the same name and behavior exists (see ostream::flush).

Parameters

os
Output stream object affected.
Because this function is a manipulator, it is designed to be used alone with no arguments in conjunction with the insertion (<<) operations on output streams (see example below).

Return Value

Argument os.

Errors are signaled by modifying the internal state flags of os:
flagerror
eofbit-
failbitMay be set if the construction of a sentry object failed.
badbitThe synchronization operation failed (including if the function catches an exception thrown by an internal operation).
When set, the integrity of the stream may have been affected.
Multiple flags may be set on os by a single operation.

If the operation sets an internal state flag of os that was registered using its member exceptions, the function throws an exception of type ios_base::failure.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Flushing files (flush manipulator)
#include <ostream>      // std::flush
#include <fstream>      // std::ofstream

int main () {

  std::ofstream outfile ("test.txt");

  for (int n=0; n<100; n++)
    outfile << n << std::flush;

  outfile.close();

  return 0;
}


This program requests test.txt to be flushed 100 times.

Data races

Modifies os.
Concurrent access to the same stream object may cause data races, except for the standard stream objects (cout, cerr, clog, wcout, wcerr and wclog) when these are synchronized with stdio (in this case, no data races are initiated, although no guarantees are given on the order in which characters from multiple threads are inserted).

Exception safety

Basic guarantee: if an exception is thrown, os is in a valid state.
It throws an exception of member type failure if the resulting error state flag of os is not goodbit and member exceptions was set to throw for that state.
Any exception thrown by an internal operation is caught and handled by the function, setting os's badbit. If badbit was set on the last call to exceptions for os, the function rethrows the caught exception.

See also