如何禁用流上的缓冲? [英] How to disable buffering on a stream?

查看:116
本文介绍了如何禁用流上的缓冲?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C中,我可以轻松地将流设置为未缓冲的I / O:

In C, I can easily set a stream to unbuffered I/O:

FILE * f = fopen( "test", "r" );
setvbuf( f, (char *)NULL, _IONBF, 0 );

如何使用C ++ IOStreams实现类似的无缓冲I / O?

How would I achieve similarly unbuffered I/O using C++ IOStreams?

推荐答案

对于文件流,您可以使用 pubsetbuf

For file streams, you can use pubsetbuf for that :

std::ifstream f;
f.rdbuf()->pubsetbuf(0, 0);
f.open("test");


C ++标准说明了 setbuf (因此 pubsetbuf code>)的文件流:

The C++ standard says the following about the effect of setbuf (and thus pubsetbuf) for file streams :


如果 setbuf(0,0)在流上发生任何I / O之前在流上调用,流
变为未缓冲的。否则结果是实现定义的。 Unbuffered表示
pbase() pptr()始终返回null并输出到文件应该尽快出现。

If setbuf(0,0) is called on a stream before any I/O has occurred on that stream, the stream becomes unbuffered. Otherwise the results are implementation-defined. "Unbuffered" means that pbase() and pptr() always return null and output to the file should appear as soon as possible.

第一句话保证上面的代码使流无缓冲。注意,一些编译器(例如gcc)在流上打开一个文件作为I / O操作,因此在打开文件之前应调用 pubsetbuf

The first sentence guarantees that the above code makes the stream unbuffered. Note that some compilers (eg. gcc) see opening a file as an I/O operation on the stream, so pubsetbuf should be called before opening the file (as above).

然而,最后一句似乎暗示这只是输出,而不是输入。我不知道这是否是一个疏忽,或者这是否是打算。咨询编译器文档可能很有用。对于gcc eg。,输入和输出都是无缓冲的(ref。 GNU C ++ Library Manual - Stream Buffers )。

The last sentence, however, seems to imply that that would only be for output, and not for input. I'm not sure if that was an oversight, or whether that was intended. Consulting your compiler documentation might be useful. For gcc eg., both input and output are made unbuffered (ref. GNU C++ Library Manual - Stream Buffers).

这篇关于如何禁用流上的缓冲?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆