Case(s) where output buffer won't flush?

Viewed 331

I am learning about iostream objects and flushing the buffer. I know when output buffers are guaranteed to be flushed and how to explicitly flush the buffer. However, I have never seen a case where output buffer is not flushed. It seems to me that output buffer gets flushed at the end of each statement even if I don't use manipulators such as endl, flush and ends.

So, is there any simple example(s) where the output buffer will not ( or at least, might often not) get flushed? I feel like I need to see such a case to really understand output buffers.

1 Answers

Depends on the system.

Take the following program as an example:

#include <iostream>
#ifdef WIN32
#include <windows.h>
#define sleep(n) Sleep((n)*1000)
#else
#include <unistd.h>
#endif

using namespace std;

int main()
{
    cout << "This is line 1";
    sleep(4);
    cout << endl;
    cout << "This is line 2" << endl;

    return 0;
}

By inspecting the program, you might surmise that the program would print This is line 1, followed by pausing for 4 seconds, then printing This is line 2.

And if you compile with Visual Studio to run on Windows, you'll get that exact behavior.

On Linux and other Unix operating systems however, the program will appear to be silent for 4 seconds before printing out both lines together. The output won't reliably flush until a new line character is encountered in the output stream.

Related