Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

c++ - How to disable buffering on a stream?

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For file streams, you can use pubsetbuf for that :

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


Explanation

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

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.

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).

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...