在C ++中有二进制内存流 [英] Are there binary memory streams in C++
问题描述
我通常使用 stringstream
写入内存中的字符串。有没有办法写入一个char缓冲区二进制模式?考虑下面的代码:
I usually use stringstream
to write into in-memory string. Is there a way to write to a char buffer in binary mode? Consider the following code:
stringstream s;
s << 1 << 2 << 3;
const char* ch = s.str().c_str();
ch
:0x313233 - 字符1,2和3的ASCII码。我正在寻找一种方法来写入二进制值本身。也就是说,我想在内存中的0x010203。问题是我想要能够写一个函数
The memory at ch
will look like this: 0x313233 - the ASCII codes of the characters 1, 2 and 3. I'm looking for a way to write the binary values themselves. That is, I want 0x010203 in the memory. The problem is that I want to be able to write a function
void f(ostream& os)
{
os << 1 << 2 << 3;
}
并决定使用什么类型的流。这样的:
And decide outside what kind of stream to use. Something like this:
mycharstream c;
c << 1 << 2 << 3; // c.data == 0x313233;
mybinstream b;
b << 1 << 2 << 3; // b.data == 0x010203;
任何想法?
推荐答案
要读取和写入二进制数据到流,包括stringstreams,请使用read()和write()成员函数。
To read and write binary data to streams, including stringstreams, use the read() and write() member functions. So
int a(1), b(2), c(3);
std::stringstream s;
s.write(reinterpret_cast<const char*>(&a), sizeof(int));
s.write(reinterpret_cast<const char*>(&b), sizeof(int));
s.write(reinterpret_cast<const char*>(&c), sizeof(int));
编辑:
使用插入和提取操作符(<< ;和>>),你最好打算创建一个派生的streambuf做正确的事情,并传递到任何流你想使用。
To make this work transparently with the insertion and extraction operators (<< and >>), your best bet it to create a derived streambuf that does the right thing, and pass that to whatever streams you want to use.
这篇关于在C ++中有二进制内存流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!