我想在将二进制数据写入文件之前暂时缓存二进制数据。这是我的想法。将二进制数据写入文件
由于我必须在此数据之前插入一个标题,指示在标题后面会有多少数据,所以我需要一种方法在将数据写入ofstream file
之前对其进行高速缓存。我决定创建ostream buffer();
,其中我可以转储所有这些数据而不写入文件。
标题写完后,我只是做file << buffer
来转储数据。
我仍然有编译器错误挣扎比如这个:
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
为什么我没有得到预期的结果?
发表一些代码。 –
我已经更新了这个问题。希望能够清除我想要做的事情。 – Pieter