C++ 包装字节流

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

以上。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值