C ++缓冲流IO

扫码查看
本文介绍了C ++缓冲流IO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解默认情况下C ++支持的所有流IO都被缓冲。



这意味着要输出的数据放入缓冲区,发送到输出设备,类似地用于输入,一旦缓冲器为空就读取数据...所有这一切都使得昂贵的系统调用的数量可以最小化。



  int main()
{
cout< Hello world\\\
;
return 0
}

我知道有缓冲发生,但如何解释呢?输出立即在屏幕上显示,所以什么可以是一个代码示例来实际看到缓冲的I / O在操作?

解决方案

尝试以下程序。 sleep(1)用于引入延迟(1秒),我使用linux,因此 sleep 我。如果你不能使它工作,尝试其他方法来延迟这个程序(例如,简单 for loop)。



在我的操作系统( Linux)中,您可以尝试增加缓冲区大小(取消注释注释的代码行) 3.2.0 )和编译器( g ++ 4.6.3 ),此程序将打印Portion1Portion2,然后打印Portion3Portion4,然后打印Portion5。 std :: endl 缓冲区,但正如您所看到的,换行符对我来说也是这样的。

  #include< iostream> 
#include< unistd.h>

using namespace std;

int main(){
//尝试取消注释以下行以增加缓冲区大小
// char mybuf [1024]
// cout.rdbuf() - > pubsetbuf(mybuf,1024);

cout<< Portion1;
sleep(1);
cout<< Portion2 \\\
;
sleep(1);
cout<< Portion3;
sleep(1);
cout<< 部分4< endl;
sleep(1);
cout<< 部分5 endl;
sleep(1);
cout<< 完成! << endl;

return 0;
}


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 output device, similarly for input, the data is read once the buffer is empty...all this is done so that number of expensive system calls could be minimized.

But how to verify this behavior in action. I mean consider the following code

int main()
{
    cout << "Hello world\n";
    return 0
}

Where does buffering come into picture here ? I know there is buffering happening, but how to explain it? The output is seen instantly on the screen, so what could be a code example to actually see buffered I/O in action ?

解决方案

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 <iostream>
#include <unistd.h>

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;
}

这篇关于C ++缓冲流IO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 23:01
查看更多