C++ 将二进制数据写入文件

C++ 将二进制数据写入文件,c++,io,ostream,C++,Io,Ostream,我想先暂时缓存二进制数据,然后才能将其写入文件。这是我的主意 由于我必须在该数据之前插入一个标头,以指示在标头之后将有多少数据,因此我需要一种方法,在将该数据写入流文件的之前将其缓存。我决定创建ostream buffer()其中我可以转储所有这些数据,而无需将其写入文件 在写入头之后,我只需执行fileostream buffer()正在声明一个名为buffer的函数,该函数不带任何参数,并返回一个ostream。另外,ostream是一个基类,您应该改用strstream。哎哟。我在注意到o

我想先暂时缓存二进制数据,然后才能将其写入文件。这是我的主意

由于我必须在该数据之前插入一个标头,以指示在标头之后将有多少数据,因此我需要一种方法,在将该数据写入流文件的
之前将其缓存。我决定创建
ostream buffer()其中我可以转储所有这些数据,而无需将其写入文件


在写入头之后,我只需执行
file
ostream buffer()
正在声明一个名为
buffer
的函数,该函数不带任何参数,并返回一个
ostream
。另外,
ostream
是一个基类,您应该改用
strstream

哎哟。我在注意到
ostream buffer之后添加了括号无法工作,因为构造函数受保护。。。我没有想清楚。我将尝试一下strstream,但我希望它不会破坏文件的二进制编码。我已经更新了问题。希望这能澄清我的想法。
error: no matching function for call to ‘TGA2Converter::writePixel(std::ostream (&)(), uint32_t&)’
note: candidate is: void TGA2Converter::writePixel(std::ostream&, uint32_t)
// This is a file. I do not want to write the binary
// data to the file before I can write the header.
ofstream file("test.txt", ios::binary);

// This is binary data. Each entry represents a byte.
// I want to write it to a temporary cache. In my
// real code, this data has to be gathered before
// I can write the header because its contents depend
// on the nature of the data.
stringstream cache;
vector<uint32_t> arbitraryBinData;
arbitraryBinData.resize(3);
arbitraryBinData[0] = 0x00;
arbitraryBinData[1] = 0xef;
arbitraryBinData[2] = 0x08;

// Write it to temporary cache
for (unsigned i = 0; i < arbitraryBinData.size(); ++i)
    cache << arbitraryBinData[i];

// Write header
uint32_t header = 0x80;     // Calculation based on the data!
file << header;

// Write data from cache
file << cache;
0000000: 8000 ef08
0000000: 3132 3830 7837 6666 6638 6434 3764 3139
0000010: 38