C++ buffered stream IO

后端 未结 3 2007
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-06 07:46

I understand that by default all stream IO supported by C++ is buffered.

This means that data to be output is put into a buffer till it is full and then sent to the

3条回答
  •  情歌与酒
    2021-01-06 08:03

    Try the following program. sleep(1) is used to introduce delay(1 second), I'm using linux, so sleep works for me. If you can't make it work, try other ways to delay this program(for example, simple for loop). You may also try increasing buffer size(uncomment commented lines of code) if you don't see any buffering effect.

    On my OS(Linux 3.2.0) and compiler(g++ 4.6.3), this program prints "Portion1Portion2" then "Portion3Portion4" and then "Portion5". std::endl guaranteed to flush buffer, but as you can see, newline character also works this way for me.

    #include 
    #include 
    
    using namespace std;
    
    int main () {
        // Try uncommenting following lines to increase buffer size
        // char mybuf[1024];
        // cout.rdbuf()->pubsetbuf(mybuf, 1024);
    
        cout << "Portion1";
        sleep(1);
        cout << "Portion2\n";
        sleep(1);
        cout << "Portion3";
        sleep(1);
        cout << "Portion4" << endl;
        sleep(1);
        cout << "Portion5" << endl;
        sleep(1);
        cout << "Done!" << endl;
    
        return 0;
    }
    

提交回复
热议问题