学过 C++ 的人都知道 iostream
,但是用流的方式来操作缓冲区好像不是那么简单。。
参考 std::streambuf::pubsetbuf 我们知道可以手动控制文件流的缓冲区大小:
// set character buffer (pubsetbuf)
#include <fstream> // std::fstream
int main () {
char mybuffer [512];
std::fstream filestr;
filestr.rdbuf()->pubsetbuf(mybuffer,512);
// operations with file stream here.
filestr.open('test.txt');
return 0;
}
于是乎尝试用 std::stringstream
读写缓冲区:
#include <sstream>
void FillBuffer(char* buffer, unsigned int size)
{
std::stringstream message;
message.rdbuf()->pubsetbuf(buffer, size);
message << "Hello" << std::endl;
message << "World!" << std::endl;
}
结果发现 basic_stringstream::basic_stringbuf
根本没有覆盖虚函数 pubsetbuf
,也就是无法替换它的默认缓冲区。
结论就是,用 StackOverflow 上这个 Setting the internal buffer used by a standard stream (pubsetbuf) 给出的方法,直接构造一个 ostream 对象:
#include <streambuf>
template <typename char_type>
struct ostreambuf : std::basic_streambuf<char_type, std::char_traits<char_type>>
{
ostreambuf(char_type* buffer, std::streamsize bufferLength) {
// set the "put" pointer the start of the buffer and record it's length.
setp(buffer, buffer + bufferLength);
}
};
int wmain()
{
char buffer[4096] = {
0 };
ostreambuf<char> ostreamBuffer(buffer, sizeof buffer);
std::ostream out(&ostreamBuffer);
out.write("abcdef",3);
std::cout << buffer;
return 0;
}
以上。